如何将Y轴从绝对频率转换为百分比(%)

2024-10-06 17:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将绝对频率转换为百分比(0%-100%),但是在我的图表中,我看到了70000%等数字。我还想显示每个堆积区域的百分比,例如bar1->;35%vs 65%等等

def to_percent(y, position):
    s = str(100 * y)
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

filter = df["CLUSTER"] == 1
plt.ylabel("Percentage")
plt.hist([df["HOUR"][filter],df["HOUR"][~filter]],stacked=True,
         color=['#8A2BE2', '#EE3B3B'], label=['1','0'])
plt.legend()

formatter = FuncFormatter(to_percent)

# Set the formatter
plt.gca().yaxis.set_major_formatter(formatter)

plt.show()

小型虚拟数据集:

^{pr2}$

Tags: totrue区域dfreturnformatter图表plt
1条回答
网友
1楼 · 发布于 2024-10-06 17:34:30

首先,集合plt.hist公司的规范化参数为True以规范化数据。在

plt.hist([df["HOUR"][filter],df["HOUR"][~filter]],stacked=True, normed = True,
         color=['#8A2BE2', '#EE3B3B'], label=['1','0'])

无法在format函数中对您的rcParams条件进行注释-但此格式字符串有效-'{:3.1%}'。在

看看这是不是你想要的:

^{pr2}$

enter image description here

相关问题 更多 >