Skip to content

Instantly share code, notes, and snippets.

@LeoHuckvale
Created February 2, 2015 16:53
Show Gist options
  • Save LeoHuckvale/89683dc242f871c8e69b to your computer and use it in GitHub Desktop.
Save LeoHuckvale/89683dc242f871c8e69b to your computer and use it in GitHub Desktop.
matplotlib - Add subplots dynamically

Useful tip from the late creator of matplotlib, John Hunter.

http://matplotlib.1069221.n5.nabble.com/dynamically-add-subplots-to-figure-td23571.html

import matplotlib.pyplot as plt

# start with one
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])

# now later you get a new subplot; change the geometry of the existing
n = len(fig.axes)
for i in range(n):
    fig.axes[i].change_geometry(n+1, 1, i+1)

# add the new
ax = fig.add_subplot(n+1, 1, n+1)
ax.plot([4,5,6])

plt.show()
@ponnhide
Copy link

ponnhide commented Apr 2, 2022

Hi, everyone.
If you are interested in how to add matplotlib subplot dynamically, I want to present patchwoklib, which I'm developing.
It allows arranging matplotlib subplots with only "/" and "|" operators like the patchwork package for ggplot.
Please refer to the following code.

import patchworklib as pw
ax1 = pw.Brick("ax1",figsize=(1,1))
ax2 = pw.Brick("ax2",figsize=(1,3)) 
ax1.set_title("ax1")
ax2.set_title("ax2") 
ax12 = ax1|ax2
ax12.savefig("ax12.png")

ax3 = pw.Brick("ax3",(2,1))
ax4 = pw.Brick("ax4",(2,2))
ax3.set_title("ax3")
ax4.set_title("ax4") 
ax34 = ax3/ax4
ax1234 = ax12 | ax34
ax1234.savefig("ax1234.png")

ax12.png
download

ax1234.png
download

Sure, more complex plots can be generated. For details, please see https://medium.com/p/bd037fe967f4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment