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?

Luca
  • 1,299
  • 1
  • 13
  • 27

2 Answers2

5

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.

ImportanceOfBeingErnest
  • 289,005
  • 45
  • 571
  • 615
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)
Sheldore
  • 35,129
  • 6
  • 43
  • 58
  • 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? – Luca Jun 17 '19 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](https://matplotlib.org/2.2.2/api/_as_gen/matplotlib.pyplot.subplot.html) for matplotlib 2 says nothing about default – Sheldore Jun 17 '19 at 14:15