Working with Matplotlib to generate plots, I don't quite understand the difference between these two ways of generating and displaying a plot:
Form 1:
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y)
plt.show()
Form 2:
import matplotlib.pyplot as plt
graph = plt.figure()
plt.plot(x, y)
graph.show()
I know they don't do the same thing, but the difference is not clear to me. I have read documentation about it, but it is not clear to me.
Can someone explain to me step by step what happens in each case?
In the first way you are creating the graph programmatically. Matplotlib saves in memory what you have called
plt.figure()
then creates a figure. Then all the calls you make to paint on the figure asplt.plot()
will act on the last figure you created by callingplt.figure()
, even the callplt.show()
.Instead, in the second you are getting the result of the figure
plt.figure()
in a variable. This variable is an instance of the figure. You can then call or apply the object'splt.show()
method to display it. If you look in the documentation of the function you will see that under the parameters, where it indicates what it returns ("Returns:"), you will see that it says that it returns an instance of the figure, the one that you are saving to later operate on it. This would be the appropriate way if we want to operate on several figures.show()
Figure
plt.figure()