2021年5月1日星期六

PYTHON - Display percent of 100 in stacked horizontal bar plot from crosstab from matplotlib in pandas

This is my piece of code. Everything is okay except it display 0% which is wrong. Here is my piece of code. What is wrong?

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()  

And here is result. I need to show actual percentage.

current figure with 0%

https://stackoverflow.com/questions/67352751/python-display-percent-of-100-in-stacked-horizontal-bar-plot-from-crosstab-fro May 02, 2021 at 11:30AM

没有评论:

发表评论