PLT的基礎用法

如代碼:

import matplotlib.pyplot as plt
import numpy as np

#準備繪圖數據
x = np.arange(0,1,0.05)
y = np.sin(2*np.pi*x)
y2 = np.cos(2*np.pi*x)
plt.plot(x,y)
plt.show()

'''
#改變顏色
plt.plot(x,y,'r')
plt.show()

#變成虛線
plt.plot(x,y,'r--')
plt.show()

#用特定符號顯示數據點
plt.plot(x,y,'r--*',label = 'sin') #label用於添加圖示例
#加標題
plt.title("My First Plot")
#給橫座標、縱座標加標籤
plt.xlabel("x label")
plt.ylabel("y label")
#設置圖像位置
plt.legend(loc = 'best')
plt.show()
'''

'''
#figure 和 subplot 繪製多個圖表
fig = plt.figure()
ax1 = fig.add_subplot(221)  #221表示創建一個兩行兩列子圖,並且這是第一個圖
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
#將上面的曲線放到ax2中
ax2.plot(x,y)
plt.show()
'''

#上面的創建方法也可以簡化爲
fig,ax = plt.subplots(2,2)
ax[0,1].plot(x,y,'g--*',label = 'sin')
ax[0,1].set(title = 'My First Plot',xlabel = 'x',ylabel = 'y')
ax[0,1].legend(loc = 'best')
#背景上添加網格線
ax[0,1].grid()

ax[0,0].plot(x,y2,'r*',label = 'cos')
ax[0,0].set(title = 'cos plot',xlabel = 'x',ylabel = 'y')
ax[0,0].legend(loc = 'best')
ax[0,0].grid()
plt.show()

#將正弦曲線和餘弦曲線繪在一張圖上
fign,axn = plt.subplots()
axn.plot(x,y,'g--*',label = 'sin')
axn.plot(x,y2,'r^',label = 'cos')
axn.set(title = 'combine',xlabel = 'x',ylabel = 'y')
axn.grid()
axn.legend('best')
plt.show()

#將圖表保存到本地
fign.savefig('myfig.png')



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章