python matplotlib保存图形而不显示

Mon*_*iks 6 python numpy matplotlib histogram

我想创建一个直方图并将其保存到文件而不在屏幕上显示.我现在的代码片段默认显示图形,我找不到任何方法来抑制显示图形.我也尝试了pyplot.hist(nrs),同样的问题.

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")
Run Code Online (Sandbox Code Playgroud)

Mon*_*iks 7

谢谢tcasewell,补充道

import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
Run Code Online (Sandbox Code Playgroud)

在导入pyplot之前解决了这个问题.