【问题标题】:python matplotlib save graph without showingpython matplotlib保存图形而不显示
【发布时间】:2015-05-21 10:11:11
【问题描述】:

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

【问题讨论】:

  • 我无法重现这种行为(matplotlib 1.3.1)。你用的是什么版本?
  • 您确定您的代码中没有plt.show()fig.show()
  • 只需将其保存为 .py 脚本并使用 python script.py 运行它。这应该有效。在不调用plt.show() 的情况下获得图形的唯一方法是在 IPython 中使用交互模式。
  • 您想使用无头后端之一(例如 Agg)。有关示例,请参见 stackoverflow.com/questions/2801882/…(那里的问题略有不同,但解决方案相同)。
  • 您可能正在使用交互式客户端 (IPython)。 plt.ioff() 将关闭自动绘图

标签: python numpy matplotlib histogram


【解决方案1】:

谢谢tcasewell,添加

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

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

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2011-06-03
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多