Python Matplotlib-使用for循环打印分组值
我试图使用for循环绘制一个按列值分组的图,而不知道该列中唯一值的数量 您可以看到下面的示例代码(没有for循环)和所需的输出 我希望每个绘图都有不同的颜色和标记(如下所示)Python Matplotlib-使用for循环打印分组值,python,python-3.x,matplotlib,pandas-groupby,Python,Python 3.x,Matplotlib,Pandas Groupby,我试图使用for循环绘制一个按列值分组的图,而不知道该列中唯一值的数量 您可以看到下面的示例代码(没有for循环)和所需的输出 我希望每个绘图都有不同的颜色和标记(如下所示) 代码如下: import pandas as pd from numpy import random df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'], columns = ['W','X','Y','Z']) df['
代码如下:
import pandas as pd
from numpy import random
df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])
df['W'] = ['10/01/2018 12:00:00','10/03/2018 13:00:00',
'10/03/2018 12:30:00','10/04/2018 12:05:00',
'10/08/2018 12:00:15']
df['W']=pd.to_datetime(df['W'])
df['Entity'] = ['C201','C201','C201','C202','C202']
print(df.head())
fig, ax = plt.subplots()
df[df['Entity']=="C201"].plot(x="W",y="Y",label='C201',ax=ax,marker='x')
df[df['Entity']=="C202"].plot(x="W",y="Y",label='C202',ax=ax, marker='o')
这是输出:
您可以首先找到
df['Entity']
的唯一值,然后循环遍历它们。要为每个实体自动生成新标记,您可以定义一些标记的顺序(比如下面的答案中的5个),这些标记将通过marker=next(marker)
重复
完成最小答案
import itertools
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
marker = itertools.cycle(('+', 'o', '*', '^', 's'))
df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])
df['W'] = ['10/01/2018 12:00:00','10/03/2018 13:00:00',
'10/03/2018 12:30:00','10/04/2018 12:05:00',
'10/08/2018 12:00:15']
df['W']=pd.to_datetime(df['W'])
df['Entity'] = ['C201','C201','C201','C202','C202']
fig, ax = plt.subplots()
for idy in np.unique(df['Entity'].values):
df[df['Entity']==idy].plot(x="W",y="Y", label=idy, ax=ax, marker=next(marker))
plt.legend()
plt.show()