9

I would like to create a histogram and save it to a file without showing it on the screen. The piece of code I have now is showing the figure by default and I cannot find any way to suppress showing the figure. I have tried pyplot.hist(nrs) as well, 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")
5
  • I can't reproduce this behaviour(matplotlib 1.3.1). What version are you using? Commented Mar 18, 2015 at 15:01
  • are you sure you don't have plt.show() or fig.show() anywhere in your code? Commented Mar 18, 2015 at 15:08
  • 2
    Just save this as a .py script and run it with python script.py. This should work. The only way you could be getting a figure without calling plt.show() is with interactive mode in IPython. Commented Mar 18, 2015 at 15:14
  • 2
    You want to use one of the headless backends (ex Agg). See stackoverflow.com/questions/2801882/… for an example (slightly different issue there, but same solution). Commented Mar 18, 2015 at 16:29
  • 4
    You might be using an interactive client (IPython). plt.ioff() would turn autoploting off. Commented Mar 18, 2015 at 20:02

1 Answer 1

7

Thank you tcasewell, adding

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

Before importing pyplot solved the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.