bloo
bloo

Reputation: 326

Python Pandas Stacked Bar Chart x-axis labels

I've got the below dataframe:

Months  Region  Open Case ID    Closed Case ID
April   APAC    648888          648888
April   US      157790  
April   UK      221456          221456
April   APAC    425700  
April   US      634156          634156
April   UK      109445  
April   APAC    442459          442459
May     US      218526  
May     UK      317079          317079
May     APAC    458098  
May     US      726342          726342
May     UK      354155  
May     APAC    463582          463582
May     US      511059  
June    UK      97186           97186
June    APAC    681548  
June    US      799169          799169
June    UK      210129  
June    APAC    935887          935887
June    US      518106  
June    UK      69279           69279

and I am getting the counts of the Open Case ID and Closed Case ID with:

df = df.groupby(['Months','Region']).count()

I am trying to replicate the below chart generated by Excel, which looks like this:

and I am getting the below with:

df[['Months','Region']].plot.bar(stacked=True, rot=0, alpha=0.5, legend=False)

enter image description here

Is there a way to get the chart generated by python closer to the chart generated by Excel in terms of how the x-axis and its labels are broken down?

Upvotes: 1

Views: 2422

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Theres are great solution for similar question to design multi index labels here. You can use the same parameters of plot with ax=fig.gca() in that solution i.e

import matplotlib.pyplot as plt

# add_line,label_len,label_group_bar_table from https://stackoverflow.com/a/39502106/4800652

fig = plt.figure()
ax = fig.add_subplot(111)
#Your df.plot code with ax parameter here
df.plot.bar(stacked=True, rot=0, alpha=0.5, legend=False, ax=fig.gca())

labels = ['' for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
ax.set_xlabel('')
label_group_bar_table(ax, df)
fig.subplots_adjust(bottom=.1*df.index.nlevels)
plt.show()

Output based on sample data:

enter image description here

Upvotes: 2

Related Questions