抱歉,您的瀏覽器無法訪問本站
本頁面需要瀏覽器支持(啟用)JavaScript
了解詳情 >

最近在用matplotlib畫圖,需要在每個圖上重新分成子圖,也就是嵌套畫圖,記錄一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.gridspec import GridSpecFromSubplotSpec
import numpy as np

x = np.linspace(0,5, 20)
y = 2*x**2 - x + 3

random_point = np.random.randn(20)
y_random = y + random_point

y_coff = np.polyfit(x, y_random, 3)
y_fun = np.poly1d(y_coff)
y_fitted = y_fun(x)



fig = plt.figure(figsize=(10, 5))
gs = GridSpec(1, 2, figure=fig)
ax0 = fig.add_subplot(gs[0,0])
# ax1 = fig.add_subplot(gs[0,1]) # 這裡要注意,被嵌套的圖盡量直接在GridSpecFromSubplotSpec,否則會有坐標重疊

# 嵌套
gs_inner = GridSpecFromSubplotSpec(2,1, subplot_spec=gs[0,1], height_ratios=[3,1], hspace=0) # 嵌套在ax1圖上
ax_i0 = fig.add_subplot(gs_inner[0])
ax_i1 = fig.add_subplot(gs_inner[1], sharex=ax_i0)


# plot
ax0.plot(x, random_point, '.-', label=r'random point')
ax0.set_xlabel(r'x')
ax0.set_ylabel(r'random point')


ax_i0.plot(x, y, '.-', label='real y')
ax_i0.plot(x, y_fitted, label='fitted y')
ax_i0.legend()
ax_i0.tick_params(labelbottom=False) # hspace=0隱藏坐標,防止重疊
ax0.set_ylabel(r'y')

ax_i1.plot(x, y_fitted/y)
ax_i1.set_ylabel(r'ratio')
ax_i1.set_xlabel(r'x')

fig.suptitle('poly fitted results') # 圖整體加標題

效果如圖:
圖片載入失敗

注意:

  • 嵌套的圖盡量直接在GridSpecFromSubplotSpec,不要ax=gs[.., …]初始化,否則會有坐標重疊
  • hspace=0時要隱藏坐標(ax0.tick_params(labelbottom=False)),防止重疊

評論



Powered by Hexo | Theme keep Volantis

本站總訪問量 總訪客數 🌎