Matplotlib can't suppress figure window

Step 1

Check whether you're running in interactive mode. The default is non-interactive, but you may never know:

>>> import matplotlib as mpl
>>> mpl.is_interactive()
False

You can set the mode explicitly to non-interactive by using

>>> from matplotlib import pyplot as plt
>>> plt.ioff()

Since the default is non-interactive, this is probably not the problem.

Step 2

Make sure your backend is a non-gui backend. It's the difference between using Agg versus TkAgg, WXAgg, GTKAgg etc, the latter being gui backends, while Agg is a non-gui backend.

You can set the backend in a number of ways:

  • in your matplotlib configuration file; find the line starting with backend:

    backend: Agg
    
  • at the top of your program with the global matplotlib function use:

    matplotlib.use('Agg')
    
  • import the canvas directly from the correct backend; this is most useful in non-pyplot "mode" (OO-style), which is what I often use, and for a webserver style of use, that may in the end prove best (since this is a tad different than above, here's a full-blown short example):

    import numpy as np
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    figure = Figure()
    canvas = FigureCanvas(figure)
    axes = figure.add_subplot(1, 1, 1)
    axes.plot(x, np.sin(x), 'k-')
    canvas.print_figure('sine.png')
    

Perhaps just clear the axis, for example:

plt.savefig("static/data.png")
plt.close()

will not plot the output in inline mode. I can't work out if is really clearing the data though.