【发布时间】:2020-12-21 12:45:01
【问题描述】:
我找不到关于如何将子图附加到已绘制图形的明确参考。关于 SO 的一些答案已经过时,大多数都不清楚,而且 mpl 文档本身并没有很好地展示这一点。
fig.add_subplot 的问题在于它会简单地绘制任何现有的轴。
【问题讨论】:
标签: python matplotlib
我找不到关于如何将子图附加到已绘制图形的明确参考。关于 SO 的一些答案已经过时,大多数都不清楚,而且 mpl 文档本身并没有很好地展示这一点。
fig.add_subplot 的问题在于它会简单地绘制任何现有的轴。
【问题讨论】:
标签: python matplotlib
在对源代码进行了一些挖掘之后,我发现了三种不同的方法。
所有示例均假定现有图形 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])