Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subplot Stacked Bar Graphs

I've got three stacked bar graphs which I have gotten to display correctly but I want to display them side by side (as opposed to three different graphs (one under the other)).

Current code that display three graphs individually is (where axX_Group are the dataframes that have my data in them).

ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Makes and Years (Pre 2000)')
ax2_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Makes and Years (2000-2009)')
ax3_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Makes and Years (2010+)')

I know I have to use the subplot function to plot the graphs on one figure but can't seem to figure out how to assign the current graphs properly.

My main problem is that all of the examples I've come across online use subplot function to assign the location of the graph (which I understand) but then plot the graphs as a function of X and Y - as follows:

 figure = plt.figure()
 ax1 = figure.add_subplot(311)
 ax2 = figure.add_subplot(312)
 ax3 = figure.add_subplot(313)

 ax1.plot(x1,y1)
 ax2.plot(x2,y2)
 ax3.plot(x3,y3)

I need to figure out how to use the ax1.plot(X, Y) portion such that I can call the .plot(stacked bar chart)

    ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Makes and Years (Pre 2000)')

So I've gotten to this but it's not working:

fig = plt.figure()
ax1_Group = fig.add_subplot(131)
ax2_Group = fig.add_subplot(132)
ax3_Group = fig.add_subplot(133)
ax1_Group.plot(ax1_Group.plot(kind='barh', stacked=True, figsize=(6,15), title='Breakdown of Makes and Years (Pre 2000)'))
ax2_Group.plot(ax2_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2000-2009)'))
ax3_Group.plot(ax3_Group.plot(kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2010+)'))

I've tried numerous things and can't quite get it. Any help would be greatly appreciated.

like image 970
CoachB Avatar asked Apr 26 '26 23:04

CoachB


1 Answers

You can use the following code:

plt.figure()
ax1 = plt.subplot(131)
ax1_Group.plot(ax1_Group.plot(ax = ax1, kind='barh', stacked=True, figsize=(6,15), title='Breakdown of Makes and Years (Pre 2000)'))

ax2 = plt.subplot(132)
ax2_Group.plot(ax2_Group.plot(ax = ax2, kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2000-2009)'))

ax3 = plt.subplot(133)
ax3_Group.plot(ax3_Group.plot(ax = ax3, kind='barh', stacked=True, figsize=(6,20), title='Breakdown of Makes and Years (2010+)'))
like image 188
Naik Avatar answered Apr 30 '26 15:04

Naik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!