Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal stacked bar chart in Matplotlib

I'm trying to create a horizontal stacked bar chart using matplotlib but I can't see how to make the bars actually stack rather than all start on the y-axis.

Here's my testing code.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])      
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00')
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0')
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0')
plt.show()

Edited to use left kwarg after seeing tcaswell's comment.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])      
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
lefts = df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts)
plt.show()

This seems to be the right approach, but it fails if there is no data for a particular bar as it's trying to add nan to a value which then returns nan.

like image 644
Jamie Bull Avatar asked May 20 '13 16:05

Jamie Bull


People also ask

How do you plot a horizontal stacked bar graph in Python?

Steps. Set the figure size and adjust the padding between and around the subplots. Create a list of years, issues_addressed and issues_pending, in accordance with years. Plot horizontal bars with years and issues_addressed data.

How do I show values in a stacked bar chart in matplotlib?

DataFrame. plot(kind='bar', stacked=True) , is the easiest way to plot a stacked bar plot. This method returns a matplotlib.


1 Answers

Since you are using pandas, it's worth mentioning that you can do stacked bar plots natively:

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

See the visualisation section of the docs.

like image 186
Andy Hayden Avatar answered Sep 17 '22 12:09

Andy Hayden