在每根柱子上显示数据需要用到plt.text()方法。目标为在每根柱子上显示百分比数据,首先导入模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib
先设置纵轴显示频率,[方法见上一篇博客]:(https://blog.csdn.net/weixin_42199251/article/details/90073622)
x=np.random.randint(0,100,500)#生成500个0到100的整数
def add_percent(y,position):#加上百分号的方法
return str(round(y*100,2))+"%"#只保留两位数
a=plt.hist(x,bins=[0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100],weights=[1./len(x)]*len(x),rwidth=0.92)#设置横坐标分类区间以及每个数据的权重,权重置为1/数据长度
formatter=FuncFormatter(add_percent)
plt.gca().yaxis.set_major_formatter(formatter)#设置y轴的坐标显示
最后需要在每根柱子上显示百分比数值:
for p,b in zip(a[0],a[1]):#a[0]是每根柱子的长度,为一个列表,a[1]就是bins列表
plt.text(b, 1.02*p, str(round(p*100,2))+"%",fontsize=8)#前两个参数确定柱子的位置,1.02*p代表在柱子顶稍高一点,第三个参数设定显示数据,fontsize规定字号
运行一下
plt.show()