21

I'm kind of new in coding and thus in python so this may sound quite dumb, but what are the main differences between .subplot() and .subplots() methods from matplotlib in python?

I didn't find this explanation anywhere else and after reading the documentation from https://matplotlib.org/ I inferred that with both methods you can create as many figures and plots as you want...so for me both of them seem to be quite the same thing and they just differ the way you can handle plots, axes, etc...or am I wrong?

Btw, I am using python3 in jupyter notebook if it makes any difference.

Cire Ty
  • 213
  • 1
  • 2
  • 4

1 Answers1

21

1. matplotlib.pyplot.subplots()

From the documentation page on matplotlib.pyplot.subplots():

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

That means you can use this single function to create a figure with several subplots with only one line of code. For example, the code below will return both fig which is the figure object, and axes which is a 2x3 array of axes objects which allows you to easily access each subplot:

fig, axes = plt.subplots(nrows=2, ncols=3)

2. matplotlib.pyplot.subplot()

In contrast, matplotlib.pyplot.subplot() creates only a single subplot axes at a specified grid position. This means it will require several lines of code to achieve the same result as matplot.pyplot.subplots() did in a single line of code above:

# first you have to make the figure
fig = plt.figure(1)

# now you have to create each subplot individually
ax1 = plt.subplot(231)
ax2 = plt.subplot(232)
ax3 = plt.subplot(233)
ax4 = plt.subplot(234)
ax5 = plt.subplot(235)
ax6 = plt.subplot(236)

or you can also use built-in method of fig:

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(234)
ax5 = fig.add_subplot(235)
ax6 = fig.add_subplot(236)

Conclusion

The code above can be condensed with a loop, but it is still considerably more tedious to use. I'd therefore recommend you use matplotlib.pyplot.subplots() since it is more concise and easy to use.

LZYan
  • 246
  • 2
  • 4
  • 2
    The same applies to `add_subplot()` where you add a subplot each time. For ex: `ax = fig.add_subplot(111)` means just a single plot with grid 1x1. `ax = fig.add_subplot(121)` would mean 1st subplot in a 1x2 grid and `ax = fig.add_subplot(122)` would mean 2nd subplot in a 1x2 grid – Sheldore Sep 07 '18 at 10:00
  • @LZYan@Bazingaa, Thanks! :) – Cire Ty Sep 07 '18 at 15:03