【问题标题】:multiple stacked bar charts on a panel (matplotlib)面板上的多个堆叠条形图(matplotlib)
【发布时间】:2017-03-28 19:29:10
【问题描述】:

我的数据框如下所示:

time Country  Share1 Share2 Share3 Share4
1990  A       10     30     50     10
1991  A       20     70     5      5
1992  A       15     15     50     20
1990  B       40     10     15     35
1991  B       70     10     10     10 

基本上,我想随着时间的推移为每个国家/地区创建堆积条形图。

类似的代码:

for values in df.country:
    values.bar(share*, over=year, stacked=True)

...该代码不起作用,但这就是我想要做的事情的要点。我想遍历每个国家(因为我有 200 个国家),而不是一一输入。谢谢! :-)

【问题讨论】:

    标签: python matplotlib bar-chart stacked-chart


    【解决方案1】:

    一旦您了解了可以从DataFrame 对象调用的绘图方法用于坐标轴和数据,这还不算太糟糕。 x 轴将是数据框的索引,每列代表一个系列(每个系列的每个 x 值都有一个值)。假设您的数据框名为df

    # set the values for the x-axis that we want to plot,
    # in this case the time values in years
    df.set_index(['time'], inplace=True)
    
    # iterate through the list of countries, and create a plot
    for country in df.Country.unique():
        # .plot.bar makes bar charts
        ax = df[df.Country==country].plot.bar(stacked=True)
        # make room for the legend, and sets in the upper right corner
        ax.set_xlim(ax.get_xlim()[0],ax.get_xlim()[1]+1)
        ax.legend(loc='upper right')
        # add the country name to the top of the chart.
        ax.set_title(country)
    

    您可以在每次迭代时保存图像文件。

    【讨论】:

    • 这很好用,谢谢。我添加了几行代码:ax.legend_.remove() 以删除图例。 plt.savefig(country+'.png') 保存国家名称。和plt.close('all') 关闭绘图,因为它占用内存
    猜你喜欢
    • 2019-05-30
    • 2020-09-26
    • 2014-08-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多