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()
最终效果
相关文章推荐
- python调用Matplotlib绘制分布点并且添加标签
- python中利用matplotlib.patches在一个坐标轴上添加画的图形
- Python 3基础教程48-Matplotlib绘制散点图和柱状图
- Python Matplotlib实现三维/四维数据的柱状图绘制
- python matplotlib 多个子图、堆积柱状图绘画
- python matplotlib 多个子图、堆积柱状图绘画
- 使用python的matplotlib(pyplot)画折线图和柱状图
- python—matplotlib数据可视化实例注解系列-----之柱状图
- 用python画柱状图以及numpy和matplotlib的安装及配置
- python 绘图添加图例显示UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x07FA3210>]
- Python matplotlib 柱状图
- python(matplotlib)画柱状图(1)
- Python matplotlib 柱状图-折线点图+除边框+标注特殊栏颜色+扁平化图表
- Python——使用matplotlib绘制柱状图
- Python 使用matplotlib画图添加标注、及移动坐标轴位置
- python+matplotlib实现礼盒柱状图实例代码
- python 使用 matplotlib.pyplot来画柱状图和饼图
- Python学习笔记(4)--Matplotlib同时画柱状图与折线图
- Python 添加图例出错:UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x07FA3210>]
- Python 使用matplotlib画图添加标注、及移动坐标轴位置