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

标签 python pandas matplotlib plot

我用 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 绘制这样的自定义图例,或者我可以用其他图形库实现类似的东西吗?另外,对于此类数据的替代绘图类型的建议,我将不胜感激。

enter image description here

最佳答案

所以在你的系列图之后你可以添加这个

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/

相关文章:

python - 比较两个不同数据框的两列并使用 If 条件创建新列

python - tcsh 中 python-shell 下划线变量的对应部分?

Python 等价于 SQL 中的不等式连接

Python Pandas 'Unnamed' 列不断出现

python - 在 Python 中验证名称的最佳方法

python - 在 SQLAlchemy 中,为什么我在关闭 session 后仍然可以提交到数据库?

python - 使用 loc 删除索引过滤的数据框

Python:如何找到分隔两个不同集群的值?

python - Matplotlib:绘制两个 x 轴,一个是线性的,一个是对数刻度

python - 如何将这个多线图更改为条形图?