pandas 条形图中的自定义图例(matplotlib) [英] Custom legend in Pandas bar plot (matplotlib)

查看:110
本文介绍了 pandas 条形图中的自定义图例(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,
)

我想创建一个如图所示的图例(图例不是由python生成的,我是手动添加的).是否可以用熊猫绘制这样的自定义图例,或者我可以使用其他图形库实现类似的功能?另外,我也很高兴为此类数据提供其他绘图类型的建议.

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.

推荐答案

因此,在系列图之后,您可以添加此

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

这篇关于 pandas 条形图中的自定义图例(matplotlib)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆