Matplotlib:子图中的缩进

2 投票
1 回答
5185 浏览
提问于 2025-04-17 14:06

我需要做几个子图,每个子图里都有一个小插图,位置要在子图的同一个自定义地方。

理论上可以用axes_grid1来实现,就像在这个例子里展示的那样,不过在inset_axeszoomed_inset_axes里的位置参数loc=对我来说不够具体。

我也试过用GridSpecget_grid_positions,但是我搞不懂它返回的参数是什么意思。

我该怎么做才能让每个子图里的插图看起来一样,而不需要把它们放在特定的位置呢?

1 个回答

4

你可以手动来做这件事:

ncols = 2
nrows = 2

inset_hfrac = .3
inset_vfrac = .3

inset_hfrac_offset = .6
inset_vfrac_offset = .6

top_pad = .1
bottom_pad = .1
left_pad = .1
right_pad = .1

hspace = .1
vspace = .1

ax_width = (1 - left_pad - right_pad - (ncols - 1) * hspace) / ncols
ax_height = (1 - top_pad - bottom_pad - (nrows - 1) * vspace) / nrows

fig = figure()

ax_lst = []
for j in range(ncols):
    for k in range(nrows):
        a_bottom = bottom_pad + k * ( ax_height + vspace)
        a_left = left_pad + j * (ax_width + hspace)

        inset_bottom = a_bottom + inset_vfrac_offset * ax_height
        inset_left = a_left + inset_hfrac_offset * ax_width

        ax = fig.add_axes([a_left, a_bottom, ax_width, ax_height])
        ax_in = fig.add_axes([inset_left, inset_bottom, ax_width * inset_hfrac, ax_height *  inset_vfrac])
        ax_lst.append((ax,ax_in))

这样做会让你失去使用 tight_layout 的功能,但你会获得更大的控制权。

撰写回答