Call pylab.savefig without displaying in ipython

I need to create a shape in a file without displaying it in an IPython laptop. In this regard, I do not understand the interaction between IPython and matplotlib.pylab . But, when I call pylab.savefig("test.png") , the current metric is displayed in addition to saving to test.png . When automating the creation of a large set of plot files, this is often undesirable. Or in a situation where an intermediate file is required for external processing by another application.

Not sure if this is a matplotlib or IPython record matplotlib .

+48
matplotlib ipython-notebook
Mar 30 '13 at 0:00
source share
2 answers

This is a matplotlib question, and you can get around this using a backend that is not displayed to the user, for example. 'Agg':

 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig('/tmp/test.png') 

EDIT: If you do not want to lose the ability to display graphs, turn off Interactive mode and call plt.show() when you are ready to display graphs:

 import matplotlib.pyplot as plt # Turn interactive plotting off plt.ioff() # Create a new figure, plot into it, then close it so it never gets displayed fig = plt.figure() plt.plot([1,2,3]) plt.savefig('/tmp/test0.png') plt.close(fig) # Create a new figure, plot into it, then don't close it so it does get displayed plt.figure() plt.plot([1,3,2]) plt.savefig('/tmp/test1.png') # Display all "open" (non-closed) figures plt.show() 
+77
Mar 30 '13 at 0:35
source share

We do not need plt.ioff() or plt.show() (if we use %matplotlib inline ). You can check the code above plt.ioff() . plt.close() plays a significant role. Try the following:

 %matplotlib inline import pylab as plt # It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes. ## plt.ioff() # Create a new figure, plot into it, then close it so it never gets displayed fig = plt.figure() plt.plot([1,2,3]) plt.savefig('test0.png') plt.close(fig) # Create a new figure, plot into it, then don't close it so it does get displayed fig2 = plt.figure() plt.plot([1,3,2]) plt.savefig('test1.png') 

If you run this code in iPython, it will display a second graph, and if you add plt.close(fig2) to the end of it, you will not see anything.

In conclusion , if you close the digit on plt.close(fig) , it will not be displayed.

+25
Aug 6 '15 at 1:23
source share



All Articles