我用 matplotlib 创建了以下直方图。如何在条形图上添加百分比而不必使用百分比本身创建新的数据框?
x = df1
fig, ax = plt.subplots()
plt.hist(x['tx'],range=[0,11],cumulative=True, density=True, bins=np.arange(11)+ 0.7,color='dimgray',edgecolor='white',width=0.6)
plt.xticks(range(11))
plt.yticks(np.arange(0, 1.1, step=0.1))
ax.set_axisbelow(True)
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1))
ax.grid(linestyle='-', linewidth='0.4', color='grey')
您可以使用函数 plt.text(x,y,s) 在绘图上打印文本,其中 x 和 y 是文本字符串 s 的位置。
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html
以下是它在您的示例中的工作方式:
array = np.random.randint(0, 11, 50)
values, x_pos, _ = plt.hist(array,range=[0,11],cumulative=True, density=True, bins=np.arange(11)+ 0.7,color='dimgray',edgecolor='white',width=0.6)
plt.xticks(range(11))
plt.yticks(np.arange(0, 1.1, step=0.1))
[plt.text(x_, val, "{0:.1f} %".format(val *100)) for x_, val in zip(x_pos, values)]
对于文本格式并选择要显示的小数位数,或者如果您想转换为百分比,您可以在https://www.geeksforgeeks.org/string-formatting-in-python/上获得更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句