20

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.

3 Answers 3

13

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())
Sign up to request clarification or add additional context in comments.

2 Comments

Does this explanation help?
that's not true. plt.subplot(111) returns a matplotlib.axes._subplots.AxesSubplot object, exactly as add_subplot, so you can do ax=plt.subplot(111)
6

pyplot.subplot is wrapper of Figure.add_subplot with a difference in behavior. Creating a subplot with pyplot.subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary. If you do not want this behavior, use the Figure.add_subplot method or the pyplot.axes function instead. More

Comments

5

It's just like what Matplotlib document says, which has also been mentioned in @afruzan's answer.

matplotlib.pyplot.subplot: Creating a new Axes will delete any pre-existing Axes that overlaps with it beyond sharing a boundary. If you do not want this behavior, use the Figure.add_subplot method or the pyplot.axes function instead.

To make it more clear, here is an illustration:

  • Use Figure.add_subplot:
import matplotlib.pyplot as plt
    
fig = plt.figure()
fig.add_subplot(131, facecolor='red')
fig.add_subplot(132, facecolor='green')
fig.add_subplot(133, facecolor='blue')
fig.add_subplot(231, facecolor='cyan')
plt.show()

enter image description here

  • Use pyplot.subplot:
import matplotlib.pyplot as plt
    
fig = plt.figure()
fig.add_subplot(131, facecolor='red')
fig.add_subplot(132, facecolor='green')
fig.add_subplot(133, facecolor='blue')
plt.subplot(231, facecolor='cyan') # overlap with subplot generated by fig.add_subplot(131, facecolor='red'), so subplot generated by fig.add_subplot(131, facecolor='red') will be removed
plt.show()

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.