【问题标题】:How to add Percentage Bar Label in Stacked Bar Chart using Python [duplicate]如何使用Python在堆积条形图中添加百分比条形标签[重复]
【发布时间】:2021-06-02 21:06:57
【问题描述】:

我正在使用以下代码绘制百分比堆积条形图

df_q1 = df.groupby(['Q01_response', 'Year']).size().reset_index().pivot(columns='Q01_response', index='Year', values=0)
df_q1 = df_q1[['Always', 'Often','Sometimes','Never']]
stacked_data = df_q1.apply(lambda x: x*100/sum(x), axis=1)
stacked_data.plot(kind="bar", stacked=True, color=['#009933', '#99ff99', '#ff99ff','#ff6666'],figsize=(15, 5))
plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
#plt.title("Mince Pie Consumption Breakdown")
plt.xlabel("Year")
plt.ylabel("Responses (%)")

如何以百分比添加条形标签?

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    我能够通过在 ax保存图形并添加以下代码块来添加标签:

      for p in ax.patches:
            width, height = p.get_width(), p.get_height()
            x, y = p.get_xy() 
            ax.text(x+width/2, 
                    y+height/2, 
                    '{:.0f} %'.format(height), 
                    horizontalalignment='center', 
                    verticalalignment='center')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 2018-10-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      相关资源
      最近更新 更多