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 2
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)
-
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– Luca2019年06月17日 14:11:43 +00:00Commented Jun 17, 2019 at 14:11 -