1. 繪製多個圖像單獨顯示(subplot)
import numpy as np
import matplotlib.pyplot as plt
#創建自變量數組
x= np.linspace(0,2*np.pi,500)
#創建函數值數組
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
#創建圖形
plt.figure(1)
#第一行第一列圖形
ax1 = plt.subplot(2,2,1)
#第一行第二列圖形
ax2 = plt.subplot(2,2,2)
#第二行
ax3 = plt.subplot(2,1,2)
#選擇ax1
plt.sca(ax1)
plt.plot(x,y1,'r-.')
plt.ylim(-1.5,1.5) #限定y axis
#選擇ax2
plt.sca(ax2)
plt.plot(x,y2,'g--')
plt.ylim(-1.5,1.5)
#選擇ax3
plt.sca(ax3)
plt.plot(x,y3,'b--')
plt.ylim(-1.5,1.5)
plt.savefig('.//result//3.6.png')
plt.show()
2.多個函數繪製於一張圖
plt.legend() 表示圖例
plt.legend(loc=' best')
其中,loc的選擇有
center upper center best lower center lower right lower left
upper right right upper left center left center right
在設置圖例之前,需要在plt.plot()中設置label
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi,500)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.cos(x)-1
plt.plot(x,y1,color = 'r',label = 'sinx') #label每個plot指定一個字符串標籤
plt.plot(x,y2,'-.', color = 'b', label = 'cosx')
plt.plot(x,y3,'--', color = 'g', label = 'cosx-1')
plt.legend(loc=' best')
plt.savefig('.//result//3.7.png')
plt.show()