1

I have a dataframe,df2 which has 6 rows and 1591 columns

           0.0.0   10.1.21  1.5.12   3.7.8  3.5.8  1.7.8 ...        
 June       1        1         4      0       0     4
 July       0        0         0      0       0     0
 August     54       0         9      0       5     0
 September  22       0         6      0       0     1
 October    0        9         5      1       4     0

I want to plot multiple of 3 columns in each panel in a figure as a stacked bar. that is column: 0.0.0 to 1.5.12 to be plotted in a separate panel and column:3.7.8 to 1.7.8 in another panel. Here is the code:

df= df2
df['key1'] = 0
df.key1.loc[:, ['0.0.0', '10.1.21', '1.5.12']].values = 1  
df.key1.loc[:,['3.7.8', '3.5.8', '1.7.8']].values = 2
df.key1.loc[:,['4.4.3', '2.2.0', '2.8.0']].values = 3

# Plot in Three Panels
distinct_keys = df['key1'].unique()
fig, axes = pyplot.subplots(len(distinct_keys), 1, sharex=True, figsize=  (3,5)) 

#{df_subset groups the rows with the same key in other to plot them in the same panel}

for i, key in enumerate(distinct_keys):
df_subset =df[df['key1']==key]

 # plot
axes[i] = df_subset.plot(kind='bar', stacked=True)
pyplot.legend(bbox_to_anchor=(1.04,1), loc="upper right")
pyplot.subplots_adjust(right=0.7)
pyplot.tight_layout(rect=[0,0,0.75,1])
pyplot.savefig("output.png", bbox_inches="tight")

but i get :IndexingError: Too many indexers

1 Answer 1

3

Initialise the subplots -

fig, axs = plt.subplots(len(df.columns) // 3, 1, sharex=True) 

Next, perform a groupby along the first axis, but don't plot yet.

gs = df.groupby(np.arange(len(df.columns)) // 3, axis=1)

Finally, zip up the axes and the groupby output, and plot each one at a time.

for (_, g), ax in zip(gs, axs):
     g.plot.bar(stacked=True, ax=ax)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot!!!!! if there were no subplots,Is there a way generally on putting the counts of stacked bars inside a particular bar ontop of it?
@Bode Unless I misunderstood, stacked=True does that on its own.
No, it doesn't, what I mean is a numeric number on top of each bar representing the total number of stacked bars inside the bar
@Bode Oh! I see... yes... that's an interesting problem. I'm not aware of how to solve it! You could open a new question though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.