40題matplotlib從入門到精通
導入
- 導入matplotlib庫簡寫爲plt
import matplotlib.pyplot as plt
import numpy as np
基本圖表
- 用plot方法畫出x=(0,10)間sin的圖像
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x))
plt.show()
3. 用加點線的方式畫出x=(0,10)間sin的圖像
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x),'-o')
plt.show()
4. 用scatter方法畫出x=(0,10)間sin的點圖像
x=np.linspace(0,10,100)
plt.scatter(x,np.sin(x))
plt.show()
5. 用餅圖的面積及顏色展示一組4維數據
rng=np.random.RandomState(0)
x=rng.randn(100)
y=rng.randn(100)
colors=rng.rand(100)
sizes=1000*rng.rand(100)
plt.scatter(x,y,c=colors,s=sizes,alpha=0.6,cmap='viridis')
plt.colorbar()
plt.show()
6. 繪製一組誤差爲±0.6的數據的誤差條圖
x=np.linspace(0,10,50)
dy=0.6
y=np.sin(x)+dy*np.random.randn(50)
plt.errorbar(x,y,yerr=dy,fmt='o',ecolor='hotpink')
plt.show()
7. 繪製一個柱狀圖
x=[1,2,3,4,5,6,7,8]
y=[3,1,4,5,8,9,7,2]
label=(['A','B','C','D','E','F','G','H'])
plt.bar(x,y,tick_label=label)
plt.show()
8. 繪製一個水平方向柱狀圖
x=[1,2,3,4,5,6,7,8]
y=[3,1,4,5,8,9,7,2]
label=(['A','B','C','D','E','F','G','H'])
plt.barh(x,y,tick_label=label)
plt.show()
9. 繪製1000個隨機值的直方圖
data=np.random.randn(1000)
plt.hist(data)
plt.show()
10. 設置直方圖分30個bins,並設置爲頻率分佈
data=np.random.randn(1000)
plt.hist(data,bins=30,histtype='stepfilled')
plt.show()
11. 在一張圖中繪製3組不同的直方圖,並設置透明度
x1=np.random.normal(0,0.8,1000)
x2=np.random.normal(-2,1,1000)
x3=np.random.normal(3,2,1000)
kwargs=dict(alpha=0.3,bins=40)
plt.hist(x1,**kwargs)
plt.hist(x2,**kwargs)
plt.hist(x3,**kwargs)
plt.show()
12. 繪製一張二維直方圖
mean=[0,0]
cov=[[1,1],[1,2]]
x,y=np.random.multivariate_normal(mean,cov,10000).T
plt.hist2d(x,y,bins=30)
plt.show()
13. 繪製一張設置網格大小爲30的六角形直方圖
mean=[0,0]
cov=[[1,1],[1,2]]
x,y=np.random.multivariate_normal(mean,cov,10000).T
plt.hexbin(x,y,gridsize=30)
plt.show()
自定義圖表元素
- 繪製x=(0,10)間sin的圖像,設置線性爲虛線
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x),'--')
plt.show()
15. 設置y軸顯示範圍爲(-1.5,1.5)
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x))
plt.ylim(-1.5,1.5)
plt.show()
16. 設置x,y軸標籤variable x,value y
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y,label='sin(x)')
plt.xlabel('variable x')
plt.ylabel('value y')
plt.show()
17. 設置圖表標題“三角函數”
plt.rcParams['font.sans-serif'] = ['SimHei'] # 步驟一(替換sans-serif字體)
plt.rcParams['axes.unicode_minus'] = False # 步驟二(解決座標軸負數的負號顯示問題)
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y,label='sin(x)')
plt.title('三角函數')
plt.show()
18. 顯示網格
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y)
plt.grid()
plt.show()
19. 繪製平行於x軸y=0.8的水平參考線
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y)
plt.axhline(y=0.8,ls='--',c='r')
plt.show()
20. 繪製垂直於x軸x<4 and x>6的參考區域,以及y軸y<0.2 and y>-0.2的參考區域
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y)
plt.axvspan(xmin=4,xmax=6,facecolor='r',alpha=0.3)
plt.axhspan(ymin=-0.2,ymax=0.2,facecolor='y',alpha=0.3)
plt.show()
21. 添加註釋文字sin(x)
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y)
plt.text(3.2,0,'sin(x)',weight='bold',color='r')
plt.show()
22. 用箭頭標出第一個峯值
x=np.linspace(0.05,10,100)
y=np.sin(x)
plt.plot(x,y)
plt.annotate('maximun',xy=(np.pi/2,1),xytext=(np.pi/2+1,1),
weight='bold',
color='r',
arrowprops=dict(arrowstyle='->',connectionstyle='arc3',color='r'))
plt.show()
自定義圖例
- 在一張圖裏繪製sin,cos的圖形,並展示圖例
x=np.linspace(0,10,100)
fig,ax=plt.subplots()
ax.plot(x,np.sin(x),label='sin')
ax.plot(x,np.cos(x),'--',label='cos')
ax.legend()
plt.show()
24. 調整圖例在左上角展示,且不顯示邊框
x=np.linspace(0,10,100)
fig,ax=plt.subplots()
ax.plot(x,np.sin(x),label='sin')
ax.plot(x,np.cos(x),'--',label='cos')
ax.legend(loc='upper left',frameon=False)
plt.show()
25. 調整圖例在畫面上方居中展示,且分成2列
x=np.linspace(0,10,100)
fig,ax=plt.subplots()
ax.plot(x,np.sin(x),label='sin')
ax.plot(x,np.cos(x),'--',label='cos')
ax.legend(frameon=False,loc='upper center',ncol=2)
plt.show()
26. 繪製sin(x),sin(x+pi/2),sin(x+pi)的圖像,並只顯示前2者的圖例
x = np.linspace(0, 10, 1000)
y=np.sin(x[:,np.newaxis]+np.pi*np.arange(0,2,0.5))
lines=plt.plot(x,y)
plt.legend(lines[:2],['first','second'])
plt.show()
27. 將圖例分不同的區域展示
fig,ax=plt.subplots()
lines=[]
styles=['-','--','-.',':']
x=np.linspace(0,10,1000)
for i in range(4):
lines+=ax.plot(x,np.sin(x-i*np.pi/2),styles[i],color='red')
ax.axis('equal')
#設置第一組標籤
ax.legend(lines[:2],['line A','line B'],loc='upper right',frameon=False)
#創建第二組標籤
from matplotlib.legend import Legend
leg=Legend(ax,lines[2:],['line C','line D'],loc='lower right',frameon=False)
ax.add_artist(leg)
plt.show()
自定義色階
- 展示色階
x=np.linspace(0,10,1000)
I=np.sin(x)*np.cos(x[:,np.newaxis])
plt.imshow(I)
plt.colorbar()
plt.show()
29. 改變配色爲’gray’
plt.imshow(I,cmap='gray')
30. 將色階分成6個離散值顯示
x=np.linspace(0,10,1000)
I=np.sin(x)*np.cos(x[:,np.newaxis])
plt.imshow(I,cmap=plt.cm.get_cmap('Blues',6))
plt.colorbar()
plt.clim(-1,1)
plt.show()
多子圖
- 在一個1010的畫布中,(0.65,0.65)的位置創建一個0.20.2的子圖
ax1=plt.axes()
ax2=plt.axes([0.65,0.65,0.2,0.3])
plt.show()
32. 在2個子圖中,顯示sin(x)和cos(x)的圖像
fig=plt.figure()
ax1=fig.add_axes([0.1,0.5,0.8,0.4],ylim=(-1.2,1.2))
ax2=fig.add_axes([0.1,0.1,0.8,0.4],ylim=(-1.2,1.2))
x=np.linspace(0,10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
plt.show()
33. 用for創建6個子圖,並且在圖中標識出對應的子圖座標
for i in range(1,7):
plt.subplot(2,3,i)
plt.text(0.5,0.5,str((2,3,i)),fontsize=18,ha='center')
plt.show()
34. 設置相同行和列共享x,y軸
fig,ax=plt.subplots(2,3,sharex='col',sharey='row')
plt.show()
35. 用[ ]的方式取出每個子圖,並添加子圖座標文字
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
for j in range(3):
ax[i,j].text(0.5,0.5,str((i,j)),fontsize=18,ha='center')
plt.show()
36. 組合繪製大小不同的子圖,樣式如下
grid=plt.GridSpec(2,3,wspace=0.4,hspace=0.3)
plt.subplot(grid[0,0])
plt.subplot(grid[0,1:])
plt.subplot(grid[1,:2])
plt.subplot(grid[1,2])
plt.show()
37. 顯示一組二維數據的頻度分佈,並分別在x,y軸上,顯示該維度的數據的頻度分佈
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T
# Set up the axes with gridspec
fig = plt.figure(figsize=(6, 6))
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
# scatter points on the main axes
main_ax.scatter(x, y,s=3,alpha=0.2)
# histogram on the attached axes
x_hist.hist(x, 40, histtype='stepfilled',
orientation='vertical')
x_hist.invert_yaxis()
y_hist.hist(y, 40, histtype='stepfilled',
orientation='horizontal')
y_hist.invert_xaxis()
plt.show()
三維圖像
- 創建一個三維畫布
from mpl_toolkits import mplot3d
fig=plt.figure()
ax=plt.axes(projection='3d')
plt.show()
39. 繪製一個三維螺旋線
ax=plt.axes(projection='3d')
zline=np.linspace(0,15,1000)
xline=np.sin(zline)
yline=np.cos(zline)
ax.plot3D(xline,yline,zline)
plt.show()
40. 繪製一組三維點
ax=plt.axes(projection='3d')
zdata=15*np.random.random(100)
xdata=np.sin(zdata)+0.1*np.random.randn(100)
ydata=np.cos(zdata)+0.1*np.random.randn(100)
ax.scatter3D(xdata,ydata,zdata,c=zdata,cmap='Reds')
plt.show()