简体   繁体   中英

How to annotate stacked bar chart with the sum of each bar (Matplotlib)?

I have a grouped bar chart and each bar is stacked.

I have annotated each section of the stack with its individual value and now I would like to sum those values and annotate the total value(height) of each bar. I would like this annotation to be on top of each bar.

This is one of the two dataframes I am working from:

             df_title = pd.DataFrame(index=['F','M'], 
             data={'<10':[2.064897, 1.573255], '10-12':[3.933137, 4.326450], '13-17':[9.242871, 16.715831],
                    '18-24':[10.226155, 12.487709], '18-24':[8.161259, 10.717797], '35-44':[5.801377, 4.916421],
                    '45-54':[3.539823, 2.851524], '55+':[1.671583, 1.769912]})

I convert both dataframes (df_title and df_comps) into numpy arrays before plotting.

df_title_concat = np.concatenate((np.zeros((len,1)), df_title.T.values), axis=1)

Here is the full code:

    df_title 
    df_comps
    len  = df_title.shape[1]
    df_title_concat = np.concatenate((np.zeros((len,1)), df_title.T.values), axis=1)
    df_comps_concat = np.concatenate((np.zeros((len,1)), df_comps.T.values), axis=1)

    fig = plt.figure(figsize=(20,10))
    ax = plt.subplot()
    title_colors = ['skyblue', 'royalblue']
    comps_colors = ['lightgoldenrodyellow', 'orange']

    for i in range(1,3):
        for j in list(range(0, df_title.shape[1]-1)):
            j += 1 

            ax_1 = ax.bar(j, df_title_concat[j,i], width=-0.4, bottom=np.sum(df_title_concat[j,:i]), color = title_colors[i-1], 
                          edgecolor='black', linewidth=3, align='edge')

            for p in ax_1.patches:
                width, height = p.get_width(), p.get_height()
                x, y = p.get_xy() 
                if height > 2:
                    ax.annotate('{:.2f}%'.format(height), (p.get_x()+0.875*width, p.get_y()+.4*height), 
                                fontsize=16, fontweight='bold', color='black')

            ax_2 = ax.bar(j, df_comps_concat[j,i], width=0.4, bottom=np.sum(df_comps_concat[j,:i]), color = comps_colors[i-1], 
                          edgecolor='black', linewidth=3, align='edge')

            for p in ax_2.patches:
                width, height = p.get_width(), p.get_height()
                x, y = p.get_xy() 
                if height > 2:
                    ax.annotate('{:.2f}%'.format(height), (p.get_x()+0.15*width, p.get_y()+.4*height), 
                                fontsize=16, fontweight='bold', color='black')

我的堆积条形图

Here is a solution:

df_title = pd.DataFrame(index=['F','M'], 
             data={'<10':[2.064897, 1.573255], '10-12':[3.933137, 4.326450], '13-17':[9.242871, 16.715831],
                    '18-24':[10.226155, 12.487709], '18-24':[8.161259, 10.717797], '35-44':[5.801377, 4.916421],
                    '45-54':[3.539823, 2.851524], '55+':[1.671583, 1.769912]})


df_title_concat = np.concatenate((np.zeros((len(df_title),1)), df_title.T.values), axis=1)


fig = plt.figure(figsize=(12,8))
ax = plt.subplot()
title_colors = ['skyblue', 'royalblue']

for i in range(1,3):
    for j in list(range(0, df_title.shape[1]-1)):
        j += 1 
        bottom=np.sum(df_title_concat[j,:i])
        ax_1 = ax.bar(j, df_title_concat[j,i], width=-0.4, bottom=bottom, color = title_colors[i-1], 
                      edgecolor='black', linewidth=3, align='edge')

        for p in ax_1.patches:
            width, height = p.get_width(), p.get_height()
            if bottom != 0:
                ax.annotate('{:.2f}%'.format(height+bottom), (p.get_x()+0.875*width, (height+bottom)+0.3), 
                            fontsize=16, fontweight='bold', color='black')

输出

However, I would suggest you to rethink the whole approach you are following and change the plot to something like:

plt.bar(df_title.columns,df_title.loc['M'])
plt.bar(df_title.columns,df_title.loc['F'],bottom=df_title.loc['M'])

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM