【问题标题】:Stacked bar showing percentage values for 2 variables in Matplotlib?堆积条显示 Matplotlib 中 2 个变量的百分比值?
【发布时间】:2021-11-17 05:34:22
【问题描述】:

我在另一篇文章中看到了堆叠百分比条形图的代码,但是在我的绘图中采用它时遇到了麻烦。 Display totals and percentage in stacked bar chart using DataFrame.plot


data = {'Paid':[8045],'Not Paid':[1533]}
df = pd.DataFrame(data, index = [''])
df['Total'] = df['Paid']+df['Not Paid']

df_rel = (df[df.columns[0:2]].div(df.iloc[0, 2])*100).round(2)
df_rel

所以我想建立一个堆积条,显示我的两个变量中的每一个的百分比值:

df_rel.plot( kind='bar',stacked = True,mark_right = True) # this is ok

for n in df_rel:
    for i, (a,b,c) in enumerate(zip(df_rel.iloc[:,:][n], df[n], df_rel[n])):
         plt.text(a -b / 2, i, str(c) + '%', va = 'center', ha = 'center')  # this gives an error.

有人可以帮我找出问题所在吗?我收到“ValueError:1318810x237 像素的图像尺寸太大。”

而且这种方法似乎很复杂,也许有人知道更好的方法。

【问题讨论】:

    标签: python-3.x pandas plot bar-chart


    【解决方案1】:

    不需要内部循环,只需计算累积的条形高度并在那里添加文本:

    Full example

    df_rel.plot( kind='bar',stacked = True,mark_right = True) # this is ok
    h = 0
    for col in df_rel:
        h += (p := df_rel[col].iat[0])      # calculate current bar height
        plt.text(0, h - p / 2, f'{p}%', va='center', ha='center')
    plt.show()
    

    【讨论】:

    • 它说语法无效?我有 python 3.6.13,这就是为什么它不能识别 ' :=' 运算符。你知道另一种方法吗?
    • := 只在行中赋值。如果你使用的是旧版本的python,你可以把它分成两行:p = df_rel[col].iat[0]; h += p
    • 谢谢你的帮助:=)
    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2022-09-28
    • 2017-08-27
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多