Python matplotlib save graph without impressions

I would like to create a histogram and save it to a file without showing it on the screen. The part of the code that I have shows the default metric, and I cannot find a way to suppress the figure. I also tried pyplot.hist (nrs), with the same problem.

import math, time, matplotlib.pyplot as plt, pylab; 
import numpy as np; 

nrs = [1.0, 2.0, 1.0, 3.0, 4.0]
freq,bins = np.histogram(nrs)
fig = plt.figure(figsize=(5,4), dpi=100); 
freq = np.append(freq, [0.0])
graph = fig.add_subplot(111);
x = graph.bar(bins, freq)

fig.savefig( "test.png")
+4
source share
1 answer

Thanks tcasewell by adding

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')

Before importing pyplot solved the problem.

+5
source

All Articles