0

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

from matplotlib import pyplot as plt, rcParams, rc_context

with rc_context():
    
    print(f'Figure backend {plt.get_backend()}')
    x = [1,2,3,4,5]
    y = [1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.scatter(x,y)
    plt.show()
    plt.close(fig)

I would like this library to be compatible with jupyter notebooks but I am having issues with the backends.

For example: In "qt" backends the plot window is closed inmediatly and in "nbAgg" backends the plot is deleted. This code reproduces the issue.

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt, rcParams, rc_context    

%matplotlib notebook
with rc_context():
    ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
    ts = ts.cumsum()
    ts.plot()
    plt.close()

One solution is removing the plt.close(fig) but that would leave the figures opened.

Another option is adding some criteria to keep/close the figures depending on the backend, but from what I have seen the nomenclature changes from one OS to another, or if running from a notebook. The latter option is not easy though.

I wonder if anyone would please share their experience to keep the matplotlib figures in notebooks.

Delosari
  • 677
  • 2
  • 17
  • 29
  • Don't close the figure at all - if you have a notebook backend, you don't need to close it. If you have an interactive backend the user should close it. However, more apropos, you may consider not doing figure management from inside the library, but rather let the user pass an axes. – Jody Klymak Jul 10 '22 at 06:57
  • Thank you @JodyKlymak for your comment. But what about those cases where it is not a notebook? How could I distinguish between the two? – Delosari Jul 10 '22 at 07:13
  • I don’t know why you want to close the figure on the user, unless you have your own close button? – Jody Klymak Jul 10 '22 at 16:28

0 Answers0