python_matplotlib DAY_21(3)面向對象畫圖plt.figure()

學習內容
初識面向對象的畫圖方式
重點
常見作圖方式有三種,pyplot,pylab,以及面向對象型
pyplot底層製作能力不足,使用簡單
pylab完全封裝MAtlab,但不推薦使用
面向對象是Matplotlib的精髓,但是難度大,定製能力強
在下面我編寫一個面向對象的畫圖方式,作出正弦圖像

1.做出一副正選圖像

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-2*np.pi,2*np.pi,100)#畫圖所需的X變量
y=np.sin(x)#畫圖所需的Y變量

fig=plt.figure()
#創建畫圖所用的‘畫圖器’
#但是沒有畫圖器這一說,我們只是抽象的將他比做成一個畫圖使用的紙張,
#顯示圖像的框架就是紙張的大小
ax=fig.add_subplot(3,3,2)
#我們可以劃分畫圖區間,劃分成3×3的畫面,畫圖畫在從左到右,在從上到下的第二個框內
t=ax.set_title('object oriented')
#設置名稱
plt.title('pyplot')
#設置畫像名稱
plt.plot(x,y)
plt.show()

2.做到在一幅圖上畫多附圖

x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.sin(x)


fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax1.plot(x,y)
ax2=fig.add_subplot(2,2,2)
ax2.plot(x,-y)
ax3=fig.add_subplot(2,2,3)
ax3.plot(x,y**2)
ax4=fig.add_subplot(2,2,4)
ax4.plot(x,2*y)
plt.show()

通過創建不同的網格ax來實現最後的顯示
在這裏插入圖片描述

3.同時畫多幅圖,不在同一張圖上顯示

fig1 = plt.figure()
ax1 = fig1.add_subplot(2, 2, 1)
ax1.plot(x, y)
fig2 = plt.figure()
ax2 = fig2.add_subplot(2, 2, 2)
ax2.plot(x, -y)
fig3 = plt.figure()
ax3 = fig3.add_subplot(2, 2, 3)
ax3.plot(x, y ** 2)
fig4 = plt.figure()
ax4 = fig4.add_subplot(2, 2, 4)
ax4.plot(x, 2 * y)
plt.show()

在上面的代碼基礎上做了修改,我們創建了4個figure,同時顯示
在這裏插入圖片描述
我們可以觀察到,最後邊同時出現了四幅圖
綜上我們就可以看出來,有多少fig=plt.figure()就會有幾幅圖
每個fig裏面有多少不同的ax(座標軸),在一幅圖上就有多少子圖,前提是自己分區域一定要合理

補充:我們在作圖的時候顯示網格圖(grid指令)
這裏介紹兩種方法
1.plt.grid(True)指令

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot(x, y)
plt.grid(True)
plt.show()

在這裏插入圖片描述
2.在figure裏面做網格
ax.grid()

fig1 = plt.figure()
ax1 = fig1.add_subplot(3, 1, 1)
ax1.plot(x, y)
ax1.grid(color='r',linewidth='2',linestyle="--")
ax2 = fig1.add_subplot(3, 1, 2)
ax2.plot(x, -y)
ax2.grid(color='b',linewidth='3',linestyle=":")
ax3 = fig1.add_subplot(3, 1, 3)
ax3.plot(x, 2*y)

plt.show()

在這裏插入圖片描述

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