Basis of creating plots

Why I can’t use ax, fig = plt.subplots() instead of fig, ax = plt.subplots() to define a figure?

The first one will return an error as shown in picture.

image

you can but they are positional arguments you’ll need change :
ax, fig = plt.subplots()
fig.boxplot(norm_reviews[num_cols].values)
fig.set_xticklabels(num_cols, rotation=90)
fig.set_ylim(0,5)
plt.show()
The names doesn’t matter

2 Likes

That’s a nice question @gaoweidong999, https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplots.html plt.subplots() returns a tuple . If you check the its source code, you’ll see the function returns fig, and axs.

def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
             subplot_kw=None, gridspec_kw=None, **fig_kw):
    fig = figure(**fig_kw)
    axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
                       squeeze=squeeze, subplot_kw=subplot_kw,
                       gridspec_kw=gridspec_kw)
    return fig, axs

Now when calling the function fig, and ax are returned in that order hence the first variable should be fig to hold the returned fig, and ax to hold the returned axs.

2 Likes