简体   繁体   English

熊猫条形图中的自定义图例(matplotlib)

[英]Custom legend in Pandas bar plot (matplotlib)

I have created a bar plot with Pandas where I show how a quantity change for some countries and I set the bar color according to each country's continent. 我用熊猫创建了一个条形图,其中显示了某些国家/地区的数量变化情况,并根据每个国家/地区的大陆设置了条形颜色。 I plot the graph using the following code. 我使用以下代码绘制图形。 The code is based on the second reply of 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,
)

I want to create a legend like the one I show in the attached image (the legend wasn't generated by python, I added manually). 我想创建一个如图所示的图例(图例不是由python生成的,我是手动添加的)。 Is it possible to draw such custom legends with pandas, or can I achieve something similar with other graphing libraries? 是否可以用熊猫绘制这样的自定义图例,还是可以用其他图形库实现类似的功能? Also I'd appreciate suggestions for alternative plot types for such type of data. 我也很感谢为此类数据提供其他绘图类型的建议。

在此处输入图片说明

So after your Series plot you could add this 因此,在系列图之后,您可以添加

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM