Including percentage breakdown in a bar chart in Python

Viewed 58

Is it possible to include percentage breakdown in a bar chart in Python?

This is my code, I want to filter frequency of words by level of income

'''

Q1 = data.iloc[:, 5:14]

SQ1 =Q1.groupby(data['Income']).agg('count')

SQ1.sort_index(ascending=False).plot(
    kind='barh',
    figsize=(10, 10),
    cmap='GnBu',
    edgecolor='black',
    title='SQ by Age', 
    fontsize=20,
    ).yaxis.label.set_visible(False)

'''

Output

enter image description here

Graph put into individual graphs to visualise distribution

'''

def plot_counts_by_Age(groupby_count_obj, Age, ax=None):
    
    #Takes a count-aggregated groupby object, an age group, and an 
    (optional) AxesSubplot, and draws a barplot for that group
    
    sort_order = groupby_count_obj.loc[Age].sort_index().index

    sns.barplot(y = groupby_count_obj.loc[Age].index, 
                x = groupby_count_obj.loc[Age].values, 
                order = sort_order, 
                palette = 'GnBu', edgecolor = 'black', 
                ax = ax
                ).set_title("{}".format(Age))


# Setup for the 4x2 subplot grid
# Note we don't want to share the x axis since we have counts
fig, ax = plt.subplots(nrows=3, ncols=2, figsize=(10, 10), sharey=True)

# ax.flatten() avoids having to explicitly reference a subplot index in ax
# Use consideration_grouped.index[:-1] because we're not plotting the under-30s
for subplot, Age in zip(ax.flatten(), list(SQ1.index)):
    plot_counts_by_Age(SQ1, Age, ax=subplot)
    
plt.tight_layout()

'''

Output

enter image description here

I need to include percentage breakdown in each bar if possible

Thank you!

0 Answers
Related