import matplotlib.pyplot as plt
import numpy as np
labels=['G1','G2','G3','G4','G5']
men_means=[20,34,30,35,37]
women_means=[25,32,34,20,25]
#x轴是由[1,2,3,4,5]组成
x=np.arange(len(labels))
width = 0.35
fig,ax = plt.subplots()
#先画第一个男性矩形
rects1=ax.bar(x-width/2,men_means,width,label='Men')
rects2=ax.bar(x+width/2,women_means,width,label='Women')
#设置图像的一些参数
ax.set_ylabel('Scores')
ax.set_title('Score by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
#为图像加上标签
#rect.get_height()是获取当前的高度,比如蓝色的第一条高度就是20
#rect.get_x()获取当前矩形的起始x轴的位置
def autolabel(rects):
for rect in rects:
height = rect.get_height()
#annotate函数是用来对图像进行标注,
#参数xy表示标注位置
# xytext表示文本位置(在xy的位置进行多少偏移)
ax.annotate('{}'.format(height),
xy=(rect.get_x()+rect.get_width()/2,height),
xytext=(0,3),
textcoords='offset points',
ha = 'center',
va = 'bottom')
autolabel(rects1)
autolabel(rects2)
#tight_layout(),作用是自动调整子图参数,使之填充整个图像区域。
fig.tight_layout()
fig.show()
结果如下,那么如何再加一列呢?来试试看
import matplotlib.pyplot as plt
import numpy as np
labels=['G1','G2','G3','G4','G5']
men_means=[20,34,30,35,37]
women_means=[25,32,34,20,25]
w_means=[10,20,30,40,50]
#x轴是由[1,2,3,4,5]组成
x=np.arange(len(labels))
x*=2
width = 0.35
fig,ax = plt.subplots()
#先画第一个男性矩形
rects1=ax.bar(x-width,men_means,width,label='Men')
rects2=ax.bar(x,women_means,width,label='Women')
rects3 = ax.bar(x+width,w_means,width,label='W')
#设置图像的一些参数
ax.set_ylabel('Scores')
ax.set_title('Score by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
#为图像加上标签
#rect.get_height()是获取当前的高度,比如蓝色的第一条高度就是20
#rect.get_x()获取当前矩形的起始x轴的位置
def autolabel(rects):
for rect in rects:
height = rect.get_height()
#annotate函数是用来对图像进行标注,
#参数xy表示标注位置
# xytext表示文本位置(在xy的位置进行多少偏移)
ax.annotate('{}'.format(height),
xy=(rect.get_x()+rect.get_width()/2,height),
xytext=(0,2),
textcoords='offset points',
ha = 'center',
va = 'bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
#tight_layout(),作用是自动调整子图参数,使之填充整个图像区域。
fig.tight_layout()
fig.show()