user13747020
user13747020

Reputation:

fig, ax = plt.subplots() meaning

I've been using matplotlib for a while and I don't actually understand what this line does.

fig, ax = plt.subplots()

Could someone explain?

Upvotes: 7

Views: 28860

Answers (1)

vanPelt2
vanPelt2

Reputation: 908

plt.subplots() is basically a (very nice) shortcut for initializing a figure and subplot axes. See the docs here. In particular,

>>> fig, ax = plt.subplots(1, 1)

is essentially equivalent to

>>> fig = plt.figure()
>>> ax = fig.add_subplot(1, 1)

But plt.subplots() is most useful for constructing several axes at once, for example,

>>> fig, axes = plt.subplots(2, 3)

makes a figure with 2 rows and 3 columns of subplots, essentially equivalent to

>>> fig = plt.figure()
>>> axes = np.empty((2,3))
>>> for i in range(2):
...     for j in range(3):
...         axes[i,j] = fig.add_subplot(2, 3, (i*j)+j+1)

I say "essentially" because plt.subplots() also has some nice features, like sharex=True forces each of the subplots to share the same x axis (i.e., same axis limits / scales, etc.). This is my favorite way to initialize a figure because it gives you the figure and all of the axes handles in one smooth line.

Upvotes: 10

Related Questions