Python中使用Matplotlib绘图示例详解(2)--带标签的条形图
- 带标签的条形图
import matplotlib import matplotlib.pyplot as plt import numpy as np labels=["G1","G2","G3","G4","G5"] men_means=[20,34,30,35,27] women_means=[25,32,34,20,25] x=np.arange(len(labels))#the label location width=0.35#the width of bars 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") #由于men和women总共占据一个width,所以为了美观,在bar中分别设置了x-width/2,x+width/2 #add some text for labels,title and custom x-axis tick labels,etc ax.set_label("Scores") ax.set_title("Scores by group and gender") ax.set_xticks(x) #切记x是从0开始的 #这里表示的设置标记的位置以及旋转等参数的设置,但是这里并不会显示具体标注的是什么 ax.set_xticklabels(labels) #ax.set_xticklabels()设置的是标注的内容 ax.legend() def autolabel(rects): """Attach a text label above each bar in *rects*,displaying its height""" for rect in rects: height=rect.get_height() ax.annotate("{}".format(height),xy=(rect.get_x()+rect.get_width()/2,height),xytext=(0,3),#3 points vertical offset textcoords="offset points",ha="center",va="bottom") autolabel(rects1) autolabel(rects2) #上述这个函数是标记图像上面的数值的 fig.tight_layout() plt.show()