This behavior happens because Matplotlib uses the same figure and axes by default unless you explicitly create a new figure or clear the current one.
plt.plot(), Matplotlib draws on the current active figure and axes.plt.plot() calls will add to the existing plot.pythonimport matplotlib.pyplot as plt plt.figure() # Create a new figure plt.plot([0, 1]) plt.show() plt.figure() # Create another new figure plt.plot([1, 0]) plt.show()
pythonimport matplotlib.pyplot as plt plt.plot([0, 1]) plt.show() plt.clf() # Clear the current figure plt.plot([1, 0]) plt.show()
plt.close() to close the current figurepythonimport matplotlib.pyplot as plt plt.plot([0, 1]) plt.show() plt.close() # Close the current figure plt.plot([1, 0]) plt.show()
plt.figure() or use %matplotlib inline and restart the kernel if needed.plt.figure() or plt.clf().Would you like more details on managing figures in Matplotlib?