JP Zhang
JP Zhang

Reputation: 816

What's the point of "plt.figure"?

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

According to offical Matplotlib document(https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure) A figure function will

"If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. "

I tried do the above on my Ipython without plt.figure, but it showed the two required pictures still.

Upvotes: 7

Views: 13556

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

There are three cases where plt.figure is useful:

  1. Obtaining a handle to a figure. In many cases it is useful to have a handle to a figure, i.e. a variable to store the matplotlib.figure.Figure instance in, such that it can be used later on. Example:

    fig = plt.figure()
    #... other code
    fig.autofmt_xdate()
    
  2. Set figure parameters. An option to set some of the parameters for the figure is to supply them as arguments to plt.figure, e.g.

    plt.figure(figsize=(10,7), dpi=144) 
    
  3. Create several figures. In order to create several figures in the same script, plt.figure can be used. Example:

    plt.figure()      # create a figure
    plt.plot([1,2,3])
    plt.figure()      # create another figure
    plt.plot([4,5,6]) # successive commands are plotted to the new figure
    

In many other cases, there would not actually be any need to use plt.figure. Using the pyplot interface, a call to any plotting command is sufficient to create a figure and you can always obtain a handle to the current figure with plt.gcf().

From another perspective it is often desired not only to have a handle to the figure but also to an axes to plot to. In such cases, the use of plt.subplots is more favorable, fig, ax = plt.subplots().

Upvotes: 10

Chiel
Chiel

Reputation: 6194

The plt.figure gives you a new figure, and depending on the given argument it opens a new figure or not. Compare:

plt.figure(1)
plt.plot(x1, y1)
plt.plot(x2, y2)

to

plt.figure(1)
plt.plot(x1, y1)
plt.figure(2)
plt.plot(x2, y2)

to

plt.figure(1)
plt.plot(x1, y1)
plt.figure(1)
plt.plot(x2, y2)

You will see that the first example is equal to the third, because you retrieve the same figure handle with the second plt.figure(1) call in the third example.

Upvotes: 6

Related Questions