matplotlib / ipympl

Matplotlib Jupyter Integration
https://matplotlib.org/ipympl/
BSD 3-Clause "New" or "Revised" License
1.57k stars 227 forks source link

Closing figures does not work #427

Open lfriedri opened 2 years ago

lfriedri commented 2 years ago

How to reproduce

%matplotlib widget

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
plt.plot(np.sin(np.linspace(0, 20, 100)))

and then

plt.close(1)

Expected behaviour

Plotting canvas disappears.

Actual behaviour

Figure becomes non-interactive (tools do not work anymore), but canvas is still visible.

Versions

sys.version: 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] ipympl version: 0.8.7 Jupyter notebook running locally in a VS code (version 1.63.2), jupyter extension v2021.11.1001550889

ianhi commented 2 years ago

I'm pretty sure this is the intended behavior. In general we are trying to have plots persist in the output until whatever is displaying the notebook (jupyterlab/vscode/jupyter notebook) chooses to clear the output.

lfriedri commented 2 years ago

Thank you for your reply.

Mmh. I think the behaviour is inconsistent with the plain python case. When I try on windows in a console:

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
fig = plt.figure(1)
plt.plot(np.sin(np.linspace(0, 20, 100)))

Then

plt.close(1)

will close the figure window.

But maybe this needs to be handled on the VS code side then?

ianhi commented 2 years ago

Can you check what the behavior is in the classic notebook (jupyter notebook) when using %matplotlib nbagg?

Mmh. I think the behaviour is inconsistent with the plain python case.

Indeed, but also the context of a notebook is different than a plain python case, in plain python there are no real guarantees about the persistence of any output, whereas persistence of outputs next to code is one of the primary benefits of a notebook.

That said I can see how this is desirable and we can try to either add a method to do this or figure out a workaround