figure.add_subplot() vs pyplot.subplot()

bmorton12 picture bmorton12 · Dec 23, 2015 · Viewed 16.4k times · Source

What is the difference between add_subplot() and subplot()? They both seem to add a subplot if one isn't there. I looked at the documentation but I couldn't make out the difference. Is it just for making future code more flexible?

For example:

fig = plt.figure()
ax = fig.add_subplot(111)

vs

plt.figure(1)
plt.subplot(111)

from matplotlib tutorials.

Answer

Mike Müller picture Mike Müller · Dec 23, 2015

If you need a reference to ax for later use:

ax = fig.add_subplot(111)

gives you one while with:

plt.subplot(111)

you would need to do something like:

ax = plt.gca()

Likewise, if want to manipulate the figure later:

fig = plt.figure()

gives you a reference right away instead of:

fig = plt.gcf()

Getting explicit references is even more useful if you work with multiple subplots of figures. Compare:

figures = [plt.figure() for _ in range(5)]

with:

figures = []
for _ in range(5):
    plt.figure()
    figures.append(plt.gcf())