Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib save graph without showing

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")
like image 989
Monique Hendriks Avatar asked Mar 18 '15 14:03

Monique Hendriks


People also ask

How do I save a figure without displaying in Python?

Avoid Display With ioff() Method We can turn the interactive mode off using matplotlib. pyplot. ioff() methods. This prevents figure from being displayed.

How do I save my matplotlib graph?

Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

Is PLT show () necessary?

draw() . Using plt. show() in Matplotlib mode is not required.


1 Answers

Thank you tcasewell, adding

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

Before importing pyplot solved the problem.

like image 175
Monique Hendriks Avatar answered Sep 22 '22 04:09

Monique Hendriks