1.簡單動畫曲線(下圖實際上應該是動態圖)
import numpy as npfrom matplotlib import pyplot as plt#導入animation創建動畫from matplotlib import animation#生成圖紙,設置坐標軸中x,y的上下限以及動態變化的元素fig=plt.figure()ax=plt.axes(xlim=(0,2),ylim=(-2,2))#調用返回的相同線條line,=ax.plot([],[],linewidth=2)#初始化函數:繪製動畫每幀的背景def init():line.set_data([],[]) return line,#繪製動畫使用函數animate,i指動畫每幀的幀號def animate(i): x=np.linspace(0,2,1000) y=np.sin(2*np.pi*(x-0.01*i))*np.cos(22*np.pi*(x-0.01*i)) line.set_data(x,y) return line,#將上面定義的函數init和animate等價起來,設置幀數,間隔#blit = True表示僅重新繪製已更改的部分animator=animation.FuncAnimation(fig,animate,init_func=init, frames=200,interval=20,blit=True)plt.show()
2.對數圖與線形圖對比
from matplotlib import pyplot as pltimport numpy as np#x=np.linspace(1,10)代表創建1-10的等差數組,默認是50個# x = np.linspace(1,10,x),x可以設置任意大小x=np.linspace(1,10)#變量y被表示為x的指數函數y=[10**el for el in x]z=[2*el for el in x]#生成圖紙,設置圖紙大小fig=plt.figure(figsize=(10,8))#添加二行二列四個子圖中的第一個子圖ax1=fig.add_subplot(2,2,1)ax1.plot(x,y,color='darkblue')#從左側看,y軸列為對數刻度,從右側看,y軸列為線性刻度ax1.set_yscale('log')#設置標題名和y軸標籤名ax1.set_title(r'Logarithmic plot of $ {10}^{x} $')ax1.set_ylabel(r'$ {y}={10}^{x} $')#為所有的兩個坐標軸和和主次刻度打開網格顯示plt.grid(b=True,which='both',axis='both')#生成第二子圖ax2=fig.add_subplot(2,2,2)ax2.plot(x,y,color='deeppink')#變量y被表示為x的簡單線性函數ax2.set_yscale('linear')ax2.set_title(r'Linear plot of $ {10}^{x} $')ax2.set_ylabel(r'$ {y}={10}^{x} $')plt.grid(b=True,which='both',axis='both')#生成第三子圖ax3=fig.add_subplot(2,2,3)ax3.plot(x,z,color='green')ax3.set_yscale('log')ax3.set_title(r'Logarithmic plot of $ {2}^{x} $')ax3.set_ylabel(r'$ {y}={2}^{x} $')plt.grid(b=True,which='both',axis='both')#生成第四子圖ax4=fig.add_subplot(2,2,4)ax4.plot(x,z,color='red')ax4.set_yscale('linear')ax4.set_title(r'Linear plot of $ {2}^{x} $')ax4.set_ylabel(r'$ {y}={2}^{x} $')plt.grid(b=True,which='both',axis='both')plt.show()
3.兩個變量之間的互相關圖形
#導入繪圖所需要的包import matplotlib.pyplot as pltimport numpy as np# 第一組數據#生成365個浮點數,在0-1中隨機生成d1 = np.random.random(365)total1 = sum(d1)av1 = total1 / len(d1)z1 = [i - av1 for i in d1]# 第二組數據為第一組數據的每個值加1d2 = [i + 1 for i in d1]total2 = sum(d2)av2 = total2 / len(d2)z2 = [i - av2 for i in d2]#生成圖紙fig = plt.figure()#繪製三行一列的子圖一ax1 = fig.add_subplot(311)ax1.plot(d1)ax1.set_xlabel("random data in 0-1")#繪製三行一列的子圖二ax2 = fig.add_subplot(312)ax2.plot(d2)ax2.set_xlabel("365 random data")#繪製三行一列的子圖三ax3 = fig.add_subplot(313)ax3.set_xlabel('Cross correlation of random data')#使用xcorr函數,轉而調用numpy包中的correlate()函數,# 計算出相互關係並將其繪製到圖表的下半部#normed=True指進行歸一化處理,如果usevlines=True,則使用Axes.vline繪製從原點到acorr的垂直線#maxlags指最大滯後數ax3.xcorr(z1, z2, usevlines=True, maxlags=None, normed=True, lw=2)ax3.grid(True)#tight_layout會自動調整子圖參數,使之填充整個圖像區域。這是個實驗特性#可能在一些情況下不工作。它僅僅檢查坐標軸標籤、刻度標籤以及標題的部分。plt.tight_layout()plt.show()