How to close figures in notebooks without conflicting with the backend?

Hello everyone. I want to say thanks for this library and also ask for advice:

I have written a small scientific library, whose functions generate plots using this design:

from matplotlib import pyplot as plt, rcParams, rc_context

plt_design = {}
with rc_context(plt_design):
    x = [1,2,3,4,5]
    y = [1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.scatter(x,y)
    plt.show()  # or plt.save_fig()
    plt.close(fig)

Also many functions use matplotlib widgets to review and select the data.

I would like to make sure there is not conflict in scripts run within a jupyter notebook but I am having issues depending on the backend with the code structure from above.

For example: In “qt” backends the plot window is closed inmediatly and in “nbAgg” backends the notebook cell appears blanck.

Maybe the solution is keeping the figures opened in notebooks. I am not sure, however, how to keep them closed for non-notebook cases.

I would appreciate any advice.

Thanks

1 Like

Hi @Vital I’m a little confused by what you mean by conflict? and also what you mean by “how to keep them closed for non-notebook cases.”

Can you describe exactly the behavior you want a user to experience?

1 Like

Side note. I peeked around your docs and saw that you recommend %matplotlib notebook - just a heads up that that will only work in jupyter notebook and not jupyter lab and starting with notebook version 7 it will not work in notebook either. The more future proof recommendation is to use %matplotlib ipympl

1 Like

Thank you @ianhi very much for your advice and insight.

The source of this issue was my own missunderstanding: I thought you always needed to include the plt.close(fig) command at the end of your scripts. I understand that while this is the good practice if saving many figures as files, it is not so critical in an scenario where the user has to close the window figures manually.

I have changed my scripts and now they work as expected for both python scripts and notebooks.

Thanks also for checking and correcting my notebook recomendations. What do you think about the %matplotlib qt will it be short lived as well? It seems to me, the the best option for working with interactive matplotlib widgets.

I don’t think that will ever stop working so long at matplotlib suppots qt as a backend. The issue with notebook is that the notebook interface is being moved to be built using jupyterlab javascript components, and the traditional notebook extensions use different APIs than the jupyterlab extension api and so are incompatible. (This is overall a very good thing, better security etc… but does break some old extensions like what is activated by %matplotlib notbeook

1 Like

Thank you very much for all the insight.