我用 Pandas 创建了一个条形图,其中显示了某些国家/地区的数量变化情况,并根据每个国家/地区的大洲设置了条形图颜色。我使用以下代码绘制图形。代码根据this question的第二次回复:
s = pd.Series(
listOfQuantities,
listOfCountiesNames
)
''' Assign color to each country based on the continent '''
colormapping = {'AF':'k','AS':'r','EU':'g','OC':'r','NA':'b','SA':'y'}
colorstring = ""
for country in listOfCountiesNames:
continent = countryToContinent[country]
colorstring += colormapping[continent]
pd.Series.plot(
s,
kind='bar',
color=colorstring,
grid=False,
)
我想创建一个图例,就像我在附图中显示的那样(图例不是由 python 生成的,我手动添加的)。是否可以用 pandas 绘制这样的自定义图例,或者我可以用其他图形库实现类似的东西吗?另外,对于此类数据的替代绘图类型的建议,我将不胜感激。
最佳答案
所以在你的系列图之后你可以添加这个
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
NA = mpatches.Patch(color='blue', label='North America')
EU = mpatches.Patch(color='green', label='Europe')
AP = mpatches.Patch(color='red', label='Asia/Pacific')
SA = mpatches.Patch(color='yellow', label='South America')
plt.legend(handles=[NA,EU,AP,SA], loc=2)
plt.show()
关于python - Pandas 条形图中的自定义图例 (matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29639973/