简体   繁体   中英

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

My df contains three columns of monthly data. 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'] . So just:

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

You can choose the order (bottom, middle, top) , like this:

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

will put Yf at the bottom, then Ls , and Lc on top. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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