import numpy as np
import matplotlib.pyplot as plt
#防止汉字乱码
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
#在柱上显示代表的数量
def autolabel(rects):
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() * 0.25, 1.01 * height, '%s' % float(height))
def autolabel_age(rects):
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() * 0.25, 1.02 * height, '%.6s' % float(height /5.0))#返回原本
#成绩按各科汇总
data_a = [90,80,66] #语文
data_b = [90,85,77] #数学
data_c = [90,82,80.5] #体育
data_age = [10,9,12] #岁
data_age = [10 * 5.0,9 * 5.0,12 * 5.0]#把年龄处理成和成绩一个维度,显示时再处理回来
#数据组的名称
names = ["小明","小刚","小华"] #x轴标题 #第n轮
#逐个画出n组数据
width = 0.2 # 条形宽度 改组范围内能放5个数据,第6个就占到别人位置了
x = np.arange(len(names)) #x轴标题
#看图,10个学生的8科成绩,并不是一次把一个学生成绩全画,而是一次画一科:代码如下
#for i in range (x):
pa = plt.bar(x,data_a,width=width,label=u'语文',fc="g") # 这个x包含两个位置,画第一组数据 #在x位置画listy21的值,并打印图标
pb = plt.bar(x + width,data_b,width=width,label=u'数学',fc="r")# 画第二组数据
pc = plt.bar(x + width * 2,data_c,width=width,label=u'体育',fc="b")# 画第三组数据
page=plt.bar(x + width * 3,data_age,width=width,label=u'年龄',fc="brown")# 画第四组数据
autolabel(pa) #在柱上标数字
autolabel(pb)
autolabel(pc)
autolabel_age(page)
plt.xticks(x + width / 2,names) #原来这里是刻度值,现在把x轴标题替换为横坐标显示
plt.title(u"各人成绩")
plt.legend() #图例
plt.xlabel('成绩')
plt.savefig('./plot.png') #存图
plt.show()
参考:https://blog.csdn.net/run_se/article/details/109865506
https://blog.csdn.net/hhhhhhhhgggkkk/article/details/108976517