python matplotlib保存图形而不显示

2024-03-28 21:49:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个直方图并保存到一个文件中,而不在屏幕上显示它。我现在拥有的代码在默认情况下是显示图形的,我无法找到任何方法来抑制显示图形。我也试过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")

Tags: 文件代码import图形屏幕asnpfig
1条回答
网友
1楼 · 发布于 2024-03-28 21:49:10

谢谢你,Tcaswell,加上

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

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

相关问题 更多 >