pyplot
maintains a global registry of figures (it is stashed in the call to plt.figure(...)
) and IPython / Jupyter will make sure they get shown (as in most cases it is better to err on the side of showing plots you did not want than to not show plots you did want!). If you only need the figure inside of the function you can do:
from matplotlib.figure import Figure
def func():
fig = Figure()
ax = fig.subplots()
ax.plot(...)
fig.savefig('/tmp/output.png')
return None
In this case pyplot
will not keep a reference to your figure and it will be gargabe collected when the function returns.
This will work out of the box with mpl3.1+, for older version you will need to add
from matplotlib.backend_bases import FigureCanvasBase
FigureCanvasBase(fig)
after you create the figure.