Issue
I am self-learning python, and I am very confused by the matplotlib package.
when plotting, is it really necessary to use the below code?
fig = plt.figure()
I thought the code was to define an empty canvas, then we can add subplots to the canvas, but I also see lots of cases where this code is not included, and plt.plot() or plt.subplot() is directly used.
- what are the differences between ax and axes? I used to think both were subplot variables, but later I find that axes is sometimes used as variables and sometimes as arguments in plotting, for instance:
as variables, from this post:
fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(12, 8))
as an argument, from this post
n = len(fig.axes)
Any help would be much appreciated.
Solution
It is possible to plot without setting any variables. Example:
plt.figure()
plt.plot([1, 2], [5, 8])
plt.show()
You must initialize your figure somewhere, hence plt.figure()
. As you pointed out, you can also use plt.subplots()
:
fig, ax = plt.subplots()
ax.plot([1, 2], [5, 8])
plt.show()
Note that we did not set the ncols
and nrows
keyword arguments. As the default value for both is 1
, we get a single axis (which is why I chose the variable name ax
). For n × 1
or 1 × n
subplots, the second variable returned by plt.subplots()
is a one-dimensional array.
fig, axes = plt.subplots(ncols=1, nrows=2)
axes[0].plot([1, 2], [5, 8])
axes[1].plot([2, 3], [9, 3])
In the case of m × n
subplots (m, n > 1
), axes
is a two-dimensional array.
fig, axes = plt.subplots(ncols=2, nrows=2)
axes[0][0].plot([1, 2], [5, 8])
axes[1][0].plot([2, 3], [9, 3])
axes[0][1].plot([3, 4], [5, 8])
axes[1][1].plot([4, 5], [9, 3])
Whether you use ax
or axes
as the name for the second variable is your own choice, but axes
suggests that there are multiple axes and ax
that there is only one. Of course, there are also other ways to construct subplots, as shown in your linked post.
Answered By - tim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.