On JupyterLab with `%jupyter widget` why running a cell once with:
```python import matplotlib.pyplot as plt
plt.plot([0, 1]) plt.show() ```
then:
```python plt.plot([1, 0]) plt.show() ```
results in the second figure also containing the first figure `plot`?
Feb 22, 2:42pm
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.
Why does this happen?
When you call plt.plot(), Matplotlib draws on the current active figure and axes.
If you don't create a new figure or clear the current one, subsequent plt.plot() calls will add to the existing plot.
This is why your second plot contains both the first and second lines.
How to Fix It
Option 1: Create a new figure for each plot
python
import 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()
Option 2: Clear the current figure before plotting again
python
import matplotlib.pyplot as plt
plt.plot([0, 1])
plt.show()
plt.clf() # Clear the current figure
plt.plot([1, 0])
plt.show()
Option 3: Use plt.close() to close the current figure
python
import matplotlib.pyplot as plt
plt.plot([0, 1])
plt.show()
plt.close() # Close the current figure
plt.plot([1, 0])
plt.show()
Best Practice in Jupyter
If you want each cell to produce a fresh plot, always start with plt.figure() or use %matplotlib inline and restart the kernel if needed.
If you want to overlay plots intentionally, omit plt.figure() or plt.clf().
Would you like more details on managing figures in Matplotlib?
Feb 22, 2:42pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.