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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29639973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:12:13  来源:igfitidea点击:

Custom legend in Pandas bar plot (matplotlib)

pythonpandasmatplotlibplot

提问by Vasilis

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:

我用 Pandas 创建了一个条形图,在其中展示了某些国家/地区的数量变化情况,并根据每个国家/地区的大陆设置了条形颜色。我使用以下代码绘制图形。该代码基于此问题的第二个回复:

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

我想创建一个像我在附加图像中显示的图例(图例不是由 python 生成的,我手动添加的)。是否可以用Pandas绘制这样的自定义图例,或者我可以用其他图形库实现类似的功能吗?另外,我很感激有关此类数据的替代绘图类型的建议。

enter image description here

在此处输入图片说明

回答by Bob Haffner

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