抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)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

本站总访问量 总访客数 🌎