python - 面板上的多个堆叠条形图(matplotlib)

标签 python matplotlib bar-chart stacked-chart

我的数据框如下所示:

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 个国家/地区),而不是一一输入。谢谢你! :-)

最佳答案

一旦您了解可以从 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)

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

enter image description here

关于python - 面板上的多个堆叠条形图(matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600969/

相关文章:

c# - 使用 python.net 获取 C# 枚举描述?

python - 如何在 matplotlib 中使用单个 plot 命令绘制多色曲线

python matplotlib ax.get_xticks() 无法获取当前 xtick 位置

r - 如何在 R 中使用 ggplot 绘制排序的频率条形图?

android - 如何在android中绘制条形图?

r - 更改条形图中条的宽度 (R)

python - 无法将 django 迁移应用到 postgres 数据库

python - 如何在 Django 中将行调整为列?

python - 空值如何与python中的数组值匹配

python - Pandas 时间序列图设置 x 轴主要和次要刻度和标签