PYTHON-从matplotlib中的交叉表在堆叠水平条形图中显示100%的百分比

PYTHON-从matplotlib中的交叉表在堆叠水平条形图中显示100%的百分比,python,pandas,matplotlib,bar-chart,stacked,Python,Pandas,Matplotlib,Bar Chart,Stacked,这是我的代码。 一切正常,但它显示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='uppe

这是我的代码。 一切正常,但它显示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()
这是结果。我需要显示实际的百分比


由于这是一个水平的
barh()
,因此
text()
字符串应该是
width
,而不是
height

“{.0f}%.”格式(rec.get_width()),

您可以发布数据帧的一部分吗?请更正语法。当我将行“{.0f}%.”替换为“{.0f}%.”时,它不起作用。format(rec.get_width())