简体   繁体   English

子图中的堆叠条使用具有两列以上的 df

[英]Stacked-bar in sub-plot using df with more than two columns

My df contains three columns of monthly data.我的df包含三列每月数据。 Here is the file. 是文件。
I want to plot all three columns for each month on top each other in a subplot using a stacked-bar.我想使用堆叠条在子图中将每个月的所有三列相互叠加。 This is one of many codes I have tried:这是我尝试过的许多代码之一:

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

It creates a single plot with bars hang strangely (see Figure below).它创建了一个带有奇怪悬挂的条形图(见下图)。
在此处输入图片说明

I want to put it in a subplot and all columns are stacked together.我想把它放在一个子图中,所有的列都堆叠在一起。 So, the highest points in each month are the sum of the three parameters in corresponding months.因此,每个月的最高点是相应月份三个参数的总和。 I also want to have the freedom to arrange which parameter should go to the bottom, middle, and top.我也想有自由安排哪个参数应该放在底部、中间和顶部。
I want something like this.我想要这样的东西。
在此处输入图片说明 Searched on the internet, no solution yet.网上搜了下,还没解决。

Remove the bottom=df['Yf'] as this tells plt to place the bars at the heights of df['Yf'] .删除bottom=df['Yf']因为这告诉plt将条形放置在df['Yf']的高度。 So just:所以就:

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

You can choose the order (bottom, middle, top) , like this:您可以选择顺序(bottom, middle, top) ,如下所示:

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

will put Yf at the bottom, then Ls , and Lc on top.Yf放在底部,然后LsLc在顶部。 Output:输出:

在此处输入图片说明

This workaround gives what I need.这个解决方法提供了我需要的东西。

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

在此处输入图片说明

Thought there was a single line ax1.bar solution.以为有一行ax1.bar解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM