在 matplotlib 中,fig.add_subplot(111) 可能是最常用的命令之一。它常用於實現基於數據可視化的圖形。在這篇文章中,我們將從多個方面對其進行詳細的闡述。
一、基礎概念
subplot 是指在一個圖中,劃分成多個小的坐標系以便於顯示不同的圖。fig.add_subplot() 函數就可以實現在一個大的圖中添加子圖。其中,111 意味着我們創建的是一個 1 行 1 列的子圖。如果我們需要創建多個子圖,可以按照不同的行列進行配置例如:fig.add_subplot(221)、fig.add_subplot(222)、fig.add_subplot(223) 等等。
下面是一個簡單的例子:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 50)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'b-', label='sine')
plt.show()
在這個例子中,我們使用了 fig.add_subplot(111) 來創建一個子圖,其中 x,y 是我們需要顯示的數據,將其作為參數傳遞給ax.plot() 函數實現繪圖。
二、添加多個子圖
在圖像顯示時,往往需要添加多個子圖,顯示不同的數據或者進行不同的圖形展示。此時,我們需要調用 add_subplot() 函數,輸入不同的參數來實現不同的圖形布局配置。
例如,我們可以通過以下代碼在一個 2×2 的子圖中繪製四個子圖:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(x, y, 'b-', label='sine')
ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(x, y, 'r-', label='cosine')
ax3 = fig.add_subplot(2, 2, 3)
ax3.hist(y, bins=30)
ax4 = fig.add_subplot(2, 2, 4)
ax4.scatter(x, y)
plt.show()
在上述代碼中,我們首先創建了一個 2×2 的大圖。通過 add_subplot() 函數,我們分別在圖中的不同位置添加了四幅子圖。ax1、ax2、ax3、ax4 分別代表四個子圖的句柄,通過對其進行操作,就能夠實現對不同子圖的設置。
三、多元數據可視化
fig.add_subplot(111) 還可以用於繪製多元數據可視化圖形。例如,我們可以使用 matplotlib 實現氣泡圖,其中 x,y 表示不同特徵值,z 表示點大小,c 表示點的顏色:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(30)
y = np.random.rand(30)
z = np.random.rand(30) * 1000
c = np.random.rand(30)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.scatter(x, y, s=z, c=c, alpha=0.6)
plt.show()
在上述代碼中,我們使用了 fig.add_subplot(111) 創建一個子圖。通過 ax.scatter() 函數,我們將數據點根據其大小(s)以及顏色(c)進行區分。從而實現了多元數據的可視化展示。
四、自定義子圖排版
在實際場景下,我們可能需要實現完全自定義的圖表布局,此時 fig.add_subplot() 函數仍然可以派上用場。例如,我們可以通過代碼實現下圖所示的自定義排版效果:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(321)
ax1.plot(x, y, 'b-', label='sine')
ax2 = fig.add_subplot(322)
ax2.plot(x, y, 'r-', label='cosine')
ax3 = fig.add_subplot(323)
ax3.hist(y, bins=30)
ax4 = fig.add_subplot(324)
ax4.scatter(x, y)
ax5 = fig.add_subplot(325)
ax5.plot(x, y, color='g')
ax6 = fig.add_subplot(326)
ax6.plot(x, y, color='y')
plt.show()
在上面的代碼中,我們創建了一個 3×2 的大圖。通過 add_subplot() 函數,我們自定義了子圖的排版,實現了類似報告的風格布局效果。
五、總結
在本篇文章中,我們從基礎概念、添加多個子圖、多元數據可視化以及自定義子圖排版等多個方面對 fig.add_subplot() 函數進行了詳細的介紹。無論是實現簡單的數據可視化還是複雜的圖表排版,fig.add_subplot() 函數都能夠幫助我們完成。
原創文章,作者:CFRK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/144254.html