我有一个数据框架,我想创建一个线形图。每个类别我想要一行,在x
轴上我想要日期,在y
轴上我想要12MKG。我不知道如何把标签贴在线条上,并使线条在每个类别上的颜色不同。
到目前为止,我已经试过了:
plt.plot(df['date'],datatoplot['12MKG'])
<表类>日期 categorie 12 mkg tbody><<tr>202001 cat1 0.9836956 202002 cat1 0.9836956 202003 cat1 0.9831461 202004 cat1 0.97206706 202005 cat1 0.9698492 202006 cat1 0.97630334 202007 cat1 0.9787234 202008 cat1 0.9810606 202009 cat1 0.9825784 202010 cat1 0.98165137 202011 cat1 0.9768116 202012 cat1 0.96666664 202101 cat1 0.9655172 202102 cat1 0.95214105 202103 cat1 0.93721974 202104 cat1 0.9419087 202105 cat1 0.93158954 202106 cat1 0.9189189 202107 cat1 0.9144603 202001 cat2 0.3118644 202002 cat2 0.3006993 202003 cat2 0.3017544 202004 cat2 0.29433963 202005 cat2 0.3030303 202006 cat2 0.30483273 202007 cat2 0.33206108 202008 cat2 0.33730158 202009 cat2 0.344 202010 cat2 0.34008098 202011 cat2 0.34051725 202012 cat2 0.3224299 202101 cat2 0.33027524 202102 cat2 0.3187773 202103 cat2 0.29338843 202104 cat2 0.28458497 202105 cat2 0.2804878 202106 cat2 0.2804878 202107 cat2 0.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()