I am a little confused about how this code works:
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
How does the fig, axes work in this case? What does it do?
Also why wouldn't this work to do the same thing:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
Thanks
read the documentation: matplotlib.pyplot.subplots
pyplot.subplots()
returns a tuplefig, ax
which is unpacked in two variables using the notationthe code
does not work because
subplots()
is a function inpyplot
not a member of the objectFigure
.There are several ways to do it. The
subplots
method creates the figure along with the subplots that are then stored in theax
array. For example:However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:
You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.
From the change log:
Example:
You can also unpack the axes in the subplots call
And set whether you want to share the x and y axes between the subplots
Like this: