3

matplotlib.figure.Figure.add_subplots() (doc) should return an axes.

However, doing

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot()
print(ax)

returns None.

Same happens for ax = fig.add_axes()

Why this happens and how can I obtain the axes handle?

asked Jun 17, 2019 at 14:05

2 Answers 2

6

You are referring to the documentation of matplotlib 3.1. In matplotlib 3.1

ax = fig.add_subplot()

adds a subplot and returns it.

However you are running your code in a prior version. In matplotlib < 3.1 you will need to explicitly state the position of the subplot in the grid

ax = fig.add_subplot(111)

fig.add_axes() is a lower level function, it will add an axes (not a subplot on a grid), so it needs an argument, namely the position of the axes in figure coordinates.

answered Jun 17, 2019 at 14:13
1

You need to specify what kind of subplot you are adding as following. Here, 111 means 1 row, 1 column. The last index specifies the index of the current subplot.

If you have 1 row and 2 columns, then you will need to add twice: 121 and 122. Now, 121 would mean 1 row, 2 column and 1st subplot. Similarly, 122 would mean 1 row, 2 column and 2nd subplot

ax = fig.add_subplot(111)
print (ax)
# AxesSubplot(0.125,0.125;0.775x0.755)
answered Jun 17, 2019 at 14:09
2
  • Why this happens also with add_axes()? Moreover the doc says that the default is 111, so why is the handle not returned if I use the default value? Is this an error in the doc? Commented Jun 17, 2019 at 14:11
  • @LucaAmerio : ImportanceOfBeingEarnest's answered it. I am also using matplotlib 2.2.2 so I saw the same effect as you. Indeed docs for matplotlib 2 says nothing about default Commented Jun 17, 2019 at 14:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.