在matplotlib中向现有图形添加子图

3

我找不到一个清晰的参考来说明如何向已经绘制好的图形中添加子图。一些SO上的答案已经过时,大多数不清楚,而mpl文档本身也没有很好地展示这一点。

fig.add_subplot 的问题在于它会简单地覆盖任何现有的坐标轴。

1个回答

6

经过查找源代码,我找到了三种不同的方法来完成这个任务。

以下所有示例均假定存在一个名为fig的图和一个现有的轴ax

A) 如果你选择简单的子图几何结构

# add new subplot
ax_new = fig.add_subplot(2, 1, 2)
ax_new.plot(x, y)
# update and redraw existing axis
ax.change_geometry(2, 1, 1)

B) 如果您想使用更复杂的布局,可以使用GridSpec

# create gridspec and add new subplot
gs = fig.add_gridspec(3, 1)
ax_new = fig.add_subplots(gs[2, 0])
ax_new.plot(x, y)
# update and redraw existing axis
ax.set_subplotspec(gs[:2, 0])
ax.update_params()
ax.set_position(ax.figbox)

C) 使用 mpl 工具包中的 axes_grid

from mpl_toolkits.axes_grid1 import make_axes_locatable

divider = make_axes_locatable(ax)
# add new subplot of relative size 1 at the bottom of current axis
ax_new = divider.append_axes("bottom", 1)
ax_new.plot(x, y)

希望这可以为某些人节省时间和精力!

为什么不使用fig.add_axes([x, y, w, h])呢? - Jiadong
@ted930511 请参考https://dev59.com/4FcQ5IYBdhLWcg3wFf8- - Milo Wielondek
谢谢,我以前见过这个。 - Jiadong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接