matplotlib.figure.Figure.add_subplots() and add_axes() return None instead of axes

Viewed 2637

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?

2 Answers

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.

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)
Related