【问题标题】:PYTHON - Display percent of 100 in stacked horizontal bar plot from crosstab from matplotlib in pandasPYTHON - 在 pandas 中 matplotlib 的交叉表的堆叠水平条图中显示 100 的百分比
【发布时间】:2021-05-02 03:30:50
【问题描述】:

这是我的一段代码。 一切都很好,只是显示 0% 是错误的。 这是我的一段代码。怎么了?

import matplotlib.pyplot as plt

ax= pd.crosstab(df4['State'], df4['Status_new']).apply(lambda r: r/r.sum()*100, axis=1)
ax_1 = ax.plot.barh(figsize=(10,10),stacked=True, rot=0)
display(ax)
plt.legend(loc='upper center', bbox_to_anchor=(0.1, 1.0), title="Subject")

plt.xlabel('Status')
plt.ylabel('State')

for rec in ax_1.patches:
    height = rec.get_height()
    ax_1.text(rec.get_x() + rec.get_width() / 2, 
              rec.get_y() + height / 2,
              "{:.0f}%".format(height),
              ha='center', 
              va='bottom')

plt.show()

这是结果。我需要显示实际百分比。

【问题讨论】:

  • 你能发布你的数据框的一部分吗?
  • 能否请您纠正正确的语法。当我用“{:.0f}%”.format(rec.get_width()) 替换“{:.0f}%”.format(height) 行时,它不起作用

标签: python pandas matplotlib bar-chart stacked


【解决方案1】:

因为这是一个水平的barh(),所以text() 字符串应该是width 而不是height

"{:.0f}%".format(rec.get_width()),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2023-01-12
    • 2022-10-13
    • 2018-07-22
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多