Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

figure.add_subplot() vs pyplot.subplot()

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.

like image 861
bmorton12 Avatar asked Dec 23 '15 19:12

bmorton12


People also ask

What is the difference between PLT subplot and PLT subplots?

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].

What does add_subplot do in matplotlib?

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.

What is Pyplot subplot?

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 .

What is fig PLT figure () in Python?

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.


1 Answers

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())
like image 198
Mike Müller Avatar answered Sep 28 '22 16:09

Mike Müller