通过调用Matploylib库中的bar函数可以绘制柱状图,通过设置参数得到自己想要的柱状图。
一、函数原型
matplotlib.pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)
1.left:x轴的位置序列,一般蚕蛹rangge函数产生一个序列,也可以用字符串
2.height:y轴的数值序列
3.alpha:透明度,数值越小越透明
4.width:柱状图的宽度
5.color/facecolor:柱状图填充的颜色
6.edgecolor:图形边缘颜色
7.label:解释图像代表的含义,这个参数会位legend()函数做铺垫
8.linewidth / linewidths / lw:边缘/线的宽
二、使用
1、基本绘制
import matplotlib.pyplot as pltimport numpy as np#使用 range生成1-10的y值y = np.arange(1,10)x = range(len(y))plt.bar(x,y) plt.show()
效果见图1:

图1
2、同一个子图中绘制两个柱状图
import matplotlib.pyplot as pltimport numpy as np#使用 range生成1-10的y值y = np.arange(1,10)x = range(len(y)) plt.bar(x,y,alpha=0.6,width=0.5,color='yellow',edgecolor='red',label='My first bar',lw=3) plt.bar(x,y+1,alpha=0.4,width=0.5,color='green',edgecolor='blue',label='My second bar',lw=3) plt.show()
效果见图2:
图2
添加:plt.legend(loc='upper left')后、label内容将显示
注意设置 bar_width 使两个柱状图之间不重叠
#设置bar_width 使两个bar不会重叠import matplotlib.pyplot as pltimport numpy as np#使用 range生成1-10的y值y = np.arange(1,10)x = range(len(y))bar_width = 0.4x1 = [i+bar_width for i in x]plt.bar(x,y,alpha=0.6,width=0.3,color='yellow',edgecolor='red',label='My first bar',lw=3)plt.bar(x1,y,alpha=0.4,width=0.3,color='green',edgecolor='blue',label='My second bar',lw=3)plt.legend(loc='upper left')plt.show()
效果见图3:
图3
3、一个完整的柱状图
import matplotlib.pyplot as pltimport numpy as np#创建一个窗口plt.figure(figsize=(9,6),dpi=80)#创建一个子图plt.subplot(1,1,1)#数值设置N=7values=(20,23,25,14,17,32,33)index = np.arange(N)width = 0.4#绘制柱状图,颜色为 greenp2 = plt.bar(index,values,alpha=0.5,width=width,label="my bar",color='green')#设置标签、标题plt.xlabel('months')plt.ylabel('snow rain') plt.title('Snow rainfall')#设置x、y轴刻度值x_name=('jan','fub','mar','apr','may','jun','july') plt.xticks(index,x_name)plt.yticks(np.arange(0,64,8))#添加图例plt.legend(loc="upper left")plt.show()
效果见图4:
图4
4、创建带有差误线的叠堆图
在bar函数中使用参数bottom
#带有差误线叠堆图import matplotlib.pyplot as pltx = ('g1','g2','g3','g4','g5')man_y = (32,34,54,34,45)women_y=(23,25,27,31,29)width = 0.35#设置差误线man_error = (1,2,1,1,2)women_error = (1,1,1,2,3)#创建柱状图fig,ax = plt.subplots()plt.figure(figsize=(8,6),dpi=80)ax.bar(x,man_y,width,yerr=man_error,label='Men') ax.bar(x,women_y,width,yerr=women_error,bottom=man_y,label='womenen') ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.lengend() plt.show()
效果见图5:
图5