3

I couldn't find a clear reference on how to append subplots to an already drawn figure. Some of the answers on SO are outdated, most are unclear, and the mpl documentation itself is not doing a good job showcasing this.

The problem with fig.add_subplot is that it will simply draw over any existing axes.

Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45

1 Answers1

6

After some digging in the source code, I found three different ways to do this.

All examples assume an existing figure fig and with existing axis ax.

A) If you're opting for a simple subplot geometry

# 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) If you want to use a more complicated layout using 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) Using axes_grid from mpl toolkit

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)

Hope this saves somebody some time and digging!

Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45