使用多于两列的df在子图中使用叠加条

时间:2019-05-01 17:53:49

标签: python pandas matplotlib histogram stacked-chart

我的df包含三列每月数据。 Here是文件。
我想使用堆叠式条形图在子图中将每个月的所有三列都放在顶部。 这是我尝试过的许多代码之一:

df.plot(kind='bar', stacked=True, bottom = df['Yf'])

它创建了一个条形图,条形图奇怪地悬挂着(请参见下图)。 enter image description here

我想将其放在子图中,所有列都堆叠在一起。因此,每个月的最高点是对应月份中三个参数的总和。我还想自由地安排哪个参数应该放在底部,中间和顶部。
我想要这样的东西。
enter image description here 在互联网上搜索,尚无解决方案。

2 个答案:

答案 0 :(得分:1)

删除bottom=df['Yf'],因为这告诉plt将条形图放置在df['Yf']的高度。因此:

df.plot(kind='bar', stacked=True)

您可以选择顺序(bottom, middle, top),如下所示:

orders = ['Yf', 'Ls', 'Lc']
df[orders].plot(kind='bar', stacked=True)

Yf放在底部,然后将LsLc放在顶部。输出:

enter image description here

答案 1 :(得分:0)

此解决方法可以满足我的需求。

ax1.bar(df.index, df['Yf'],  alpha=0.7, color='green')
ax1.bar(df.index, df['Lc'],  bottom=df['Yf'], alpha=0.7, color='red')
ax1.bar(df.index, df['Ls'],  bottom=df['Yf']+df['Lc'], alpha=0.7, color='c')

enter image description here

以为只有一行ax1.bar解决方案。