用matplotlib.pyplot的subplots命令可以很方便的畫對稱的子圖,但是如果要畫非對稱的子圖(如下)就需要用GridSpec命令來控制子圖的位置和大小:
而上圖的結構可以用一下兩種方式畫:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig = plt.figure(1)
gs = GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[2, 0])
ax5 = plt.subplot(gs[2, 1])
或者
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3 ,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
更多間隔設置可以參考gridspec的官方文檔。
PS:如果是讀取圖片作為子圖的話建議用Pillow包的Image函數讀取,而非自帶的imread函數,對圖像的調整會方便很多:
ax1 = fig.add_subplot(gs[:, 0])
img = Image.open("your image")
ax1.imshow(img)