我试图插入一个legend
显示引用适当列值的映射颜色。具体来说,对于df
下面的column
条形图使用不同的colors
. 我试图用legend
.
所以预期的输出将显示:
A = green
B = blue
C = black
这是我的尝试:
import pandas as pd
df = pd.DataFrame({
'Gr1' : ['Foo','Boo','Bar','Foo','Bur','Foo','Boo','Bar','Boo'],
'Gr2' : ['A','B','B','C','A','B','C','C','A'],
'Value' : [1,2,4,6,8,20,25,29,30],
})
colors = {'A':'green', 'B':'blue', 'C': 'black'}
df.plot.bar(x='Gr1', y='Value', color = df['Gr2'].map(colors), label = 'Gr2');
我认为最好的办法是手动创建一个图例。自动图例创建通常需要将不同的数据集设置为不同的对象集。这是创建自定义 matplotlib 图例的指南。像这样添加的东西应该适合你:
from matplotlib.patches import Patch
legend_elements = [Patch(facecolor=c, label=x) for x, c in colors.items()]
ax.legend(handles=legend_elements)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句