1.垂直柱状图:bar
import matplotlib.pyplot as plt
import numpy as np
#绘制垂直和水平柱状图
#bar, barh
#垂直柱状图bar(X,Y)
y = [30,53,12,45]
#X,0,1,2,3
x = range(len(y))
plt.bar(x,y,facecolor='b',edgecolor='r',width=0.5)
plt.show()
width:要设置小于相邻柱状最小间隔,否则柱图会重叠
#width:指两个柱状之间的距离,一般要小于柱距离的最小值
#plt.bar([1980,1988,1995,2000],[1000,2000,3000,4000],width=1)
2.水平柱状图:barh
#水平柱状图
#plt.barh(x, y, facecolor='b', edgecolor='r', height=0.5)
plt.show()
3.同时绘制多组柱状图
import matplotlib.pyplot as plt
data = [[5,25,50,20],
[4,34,65,16],
[6,24,53,19]]
plt.bar(range(4),data[0],width=0.25)
plt.bar([x+0.25 for x in range(4)],data[1],width=0.25)
plt.bar([x+0.5 for x in range(4)],data[2],width=0.25)
plt.show()
多组水平柱状图
plt.barh(range(4),data[0],height=0.25)
plt.barh([x+0.25 for x in range(4)],data[1],height=0.25)
plt.barh([x+0.5 for x in range(4)],data[2],height=0.25)
plt.show()
4.叠加柱状图
import matplotlib.pyplot as plt
A = [5,30,45,22]
B = [5,25,50,20]
'''
X = range(4)
plt.bar(X,A,color='b')
plt.bar(X,B,color='r',bottom=A)
plt.show()
'''
叠加柱状图的numpy实现
import numpy as np
data = np.array([[5,30,45,22],
[5,25,50,20],
[10,40,50,20]])
color_list = ['b','g','r']
#data.shape[1]:数组列数
X = np.arange(data.shape[1])
for i in range(data.shape[0]):
S = np.sum(data[:i],axis=0)
print(S)
plt.bar(X,data[i],bottom=S,color=color_list[i%len(color_list)])
print("*"*88)
plt.show()
5.直方图和盒状图:
画法与柱状图类似,不同点在于,柱状图关注坐标值;而直方图更关注分布频率
import matplotlib.pyplot as plt
import numpy as np
#柱状图:关注X/Y轴值
#直方图hist:关注趋势 hist(data,value)
#x轴:data的值
#y轴:data值出现的频率
#盒装图: boxplot(data)
data = np.random.randn(100)
print(data)
print(np.average(data))
fig,(ax1,ax2) =plt.subplots(1,2,figsize=(8,4))
print(fig)
ax1.hist(data,100)
ax2.boxplot(data)
plt.show()