图形与多行python数据框架



我有一个数据框架,我想创建一个线形图。每个类别我想要一行,在x轴上我想要日期,在y轴上我想要12MKG。我不知道如何把标签贴在线条上,并使线条在每个类别上的颜色不同。

到目前为止,我已经试过了:

plt.plot(df['date'],datatoplot['12MKG'])
<表类>日期categorie12 mkgtbody><<tr>202001cat10.9836956202002cat10.9836956202003cat10.9831461202004cat10.97206706202005cat10.9698492202006cat10.97630334202007cat10.9787234202008cat10.9810606202009cat10.9825784202010cat10.98165137202011cat10.9768116202012cat10.96666664202101cat10.9655172202102cat10.95214105202103cat10.93721974202104cat10.9419087202105cat10.93158954202106cat10.9189189202107cat10.9144603202001cat20.3118644202002cat20.3006993202003cat20.3017544202004cat20.29433963202005cat20.3030303202006cat20.30483273202007cat20.33206108202008cat20.33730158202009cat20.344202010cat20.34008098202011cat20.34051725202012cat20.3224299202101cat20.33027524202102cat20.3187773202103cat20.29338843202104cat20.28458497202105cat20.2804878202106cat20.2804878202107cat20.2631579

假设我理解了你的问题,有很多方法可以做到这一点。一种方法是循环遍历每个类别,并为每条线添加预定的颜色。如果您想使用默认的颜色映射,可以跳过颜色字典部分。甚至可以使用颜色映射来获得特定的颜色"主题"。

#If you want to control the color
color_dict = {'cat1': 'r',
'cat2': 'b'}

fig, ax = plt.subplots(1,1)
# Cycle over the categories
for cat in df['categorie'].unique():
# get the data for the relevant category
temp = df[df['categorie']==cat]
# plot the line using the 'label' keyword to add a label and 'color'
# to control the color 
ax.plot(temp['date'], temp['12MKG'], label=cat, color=color_dict[cat])
ax.legend()

最新更新