Skip to main content
 首页 » 编程设计

python之Matplotlib之使用 for 循环绘制分组值

2024年11月24日17kenshinobiy

我正在尝试使用 for 循环绘制按列值分组的图表,但不知道该列中唯一值的数量。

您可以在下面看到示例代码(没有 for 循环)和所需的输出。

我希望每个地 block 都有不同的颜色和标记(如下所示)。


这是代码:

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()