What is the difference between add_subplot()
and subplot()
? They both seem to add a subplot if one isn't there. I looked at the documentation but I couldn't make out the difference. Is it just for making future code more flexible?
For example:
fig = plt.figure()
ax = fig.add_subplot(111)
vs
plt.figure(1)
plt.subplot(111)
from matplotlib tutorials.
For example, the functions plt. subplot() and plt. subplots() may appear to be off by a single letter s , but typically the former is followed by a plotting function in the form plt. plot(data_x, data_y) whereas the latter is usually followed by ax[0,0].
The add_subplot() method figure module of matplotlib library is used to add an Axes to the figure as part of a subplot arrangement. Parameters: This accept the following parameters that are described below: projection : This parameter is the projection type of the Axes.
pyplot. subplots method provides a way to plot multiple plots on a single figure. Given the number of rows and columns , it returns a tuple ( fig , ax ), giving a single figure fig with an array of axes ax .
figure(figsize=(12,8)) creates an empty plot of the given size. plt. subplots(2, 2) creates a second plot with 4 subplots, but again with the default size. To create a plot with subplots and some given size, fig, ax_lst = plt. subplots(2, 2, figsize=(12,8)) is used.
If you need a reference to ax
for later use:
ax = fig.add_subplot(111)
gives you one while with:
plt.subplot(111)
you would need to do something like:
ax = plt.gca()
Likewise, if want to manipulate the figure later:
fig = plt.figure()
gives you a reference right away instead of:
fig = plt.gcf()
Getting explicit references is even more useful if you work with multiple subplots of figures. Compare:
figures = [plt.figure() for _ in range(5)]
with:
figures = []
for _ in range(5):
plt.figure()
figures.append(plt.gcf())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With