您的位置:首页 > 编程语言 > Python开发

Python matplotlib 柱状图 添加平均线

2019-03-28 16:46 1716 查看

直接上代码

主要是在代码中添加

[code]ax.hlines(33,-1,7,linestyles='--',colors='#4472C4',label='平均值')
[code]import matplotlib.pyplot as plt
import numpy as np

men_means = (20, 35, 30, 35, 27)
women_means = (25, 32, 34, 20, 25)
women_means2= (28, 25, 30, 40, 22)

ind = np.arange(len(men_means))  # the x locations for the groups
width = 0.2  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width / 2, men_means, width,
color='#4472C4', label='男生')

rects2 = ax.bar(ind + 0.1+width/2, women_means, width,
color='#FFFFFF', label='不男不女',edgecolor= '#ED7E32',linestyle='--')
rects3 = ax.bar(ind + 0.2+1.5*width, women_means2, width,
color='#FFFFFF',edgecolor= '#A5A5A5', label='女生',linestyle='--')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('分数')
ax.set_title('男生分布')
ax.set_xticks(ind)
ax.set_xticklabels(('语文', '数学', '英语', '文综', '理综'))
ax.hlines(33,-1,7,linestyles='--',colors='#4472C4',label='平均值')
ax.legend()

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
def autolabel(rects, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.

*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""

xpos = xpos.lower()  # normalize the case of the parameter
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height,
'{}'.format(height), ha=ha[xpos], va='bottom')

# ax.plot(men_means[:5],5,'--')

autolabel(rects1, "center")
autolabel(rects2,'center')
autolabel(rects3, "center")

plt.annotate(u"平均值", xy = (5,33), xytext = (5, 40),arrowprops=dict(facecolor='red',shrink=0.1,width=2))
plt.savefig("D:/1.jpg")
plt.show()

最终效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: