1

From my understanding of matplotlib, the figure method creates a new, blank figure, basically a "white canvas," and via, for example, plot I can add the actual plot. The show method then clears the figure:

import matplotlib.pyplot as plt

fig = plt.figure()

plt.plot([0, 1], [0, 1])
plt.show()

enter image description here

1) Now, I am wondering why the same can be achieved when no figure was created. More specifically, I am wondering how matplotlib handles this internally.

2) Is there any advantage in using plt.figure if I don't intend to manipulate figure objects?

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1])
plt.show()

1 Answer 1

1
  1. plt.plot internally calls gca (get current axes) which then calls gcf (get current figure), which returns the current (last used) figure. If there is no current figure it calls plt.figure and returns the newly created figure. So yes, weather or not you call plt.figure yourself doesn't really matter. I wouldn't say it is redundant (since it has to be done), but you can safely let matplotlib take care of it.
  2. Directly calling plt.figure if you don't intend to manipulate the figure or pass arguments to the constructor is only useful to create multiple figures to show them simultaneously when calling plt.show.

    plt.figure()
    plt.plot(1,1,'x')
    plt.figure()
    plt.plot(2,2,'o')
    plt.show()
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's a nice explanation, makes sense now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.