我的数据框如下所示:
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)
您可以在每次迭代时保存图像文件。
关于python - 面板上的多个堆叠条形图(matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600969/