【问题标题】:Custom legend in Pandas bar plot (matplotlib)Pandas 条形图中的自定义图例(matplotlib)
【发布时间】:2015-06-20 19:24:30
【问题描述】:

我使用 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 绘制此类自定义图例,或者我可以使用其他图形库实现类似的功能?我也很感激为此类数据提供替代绘图类型的建议。

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

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

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

    【讨论】:

    • 我们如何显示变量名而不是颜色。我的意思是如果我们想在图例中显示 NA、EU、AP... 而不是相应的颜色?
    • 非常感谢!
    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 2016-03-21
    • 2017-01-15
    • 2016-10-28
    • 2022-12-11
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多