4.Matplotlib繪圖--柱狀圖、直方圖、盒裝圖
阿新 • • 發佈:2018-12-17
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:指兩個柱狀之間的距離,一般要小於柱距離的最小值
#plt.bar([1980,1988,1995,2000],[1000,2000,3000,4000],width=1)
#水平柱狀圖 #plt.barh(x, y, facecolor='b', edgecolor='r', height=0.5) plt.show()
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()
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()
'''
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()
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()