Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: saving a plot and not opening it in a GUI

I'm trying to run a little program that should save my 3D scatterplot instead of opening it in a GUI. The problem is that it does both! This is the piece of code I'm talking about:

from matplotlib import pyplot
from scipy import math
from mpl_toolkits.mplot3d import Axes3D

fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')        
ax.scatter(xPosition, yPosition, zPosition, c = velocity, s = mass)
ax.set_xlim3d(-plotSize, plotSize)
ax.set_ylim3d(-plotSize, plotSize)
ax.set_zlim3d(-plotSize, plotSize)
pyplot.savefig('plot.png')

I would very much like to know how I can get a saved image of my plot without the plot being opened in a gui.

like image 426
David VdH Avatar asked Nov 01 '22 11:11

David VdH


1 Answers

You should use pylab.ioff() as hilghlight by Saullo Castro, and each time you want to save a figure use pylab.savefig('file.png'). When you don't need the figure just do a pylab.close() to close the current figure (and free memory).

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
pyplot.ioff()
fig = pyplot.figure()
# HERE your code to add things in the figure
pyplot.savefig('file.png')
pyplot.close()
like image 65
head7 Avatar answered Nov 15 '22 04:11

head7