5
votes

I'm studying matplotlib and don't know how to just save the graph and not print it on the screen.

So I've done some research on the Internet, many answers said the solution is matplotlib.use('Agg'). And it must be before importing matplotlib.pyplot or pylab.

Then when I added it in the first line of my script, it doesn't work at all.

import matplotlib
matplotlib.use('Agg') 
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning:  This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  warnings.warn(_use_error_msg)

I use Anaconda Spyder, so I restarted kernel and ran my script again, I got same wrong information.

Then I restarted kernel again and directly typed the following code in the console:

In[1]: import matplotlib as mpl

In[2]: mpl.use('Agg')

E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning:  This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  warnings.warn(_use_error_msg)

Also, if I delete 'plt.show()' at the end of script or add 'plt.ioff()', the graph will always print on the screen.


Thanks for everyone's answer. Now I have two solutions:

  1. just use plt.close() , this will not change the backend and the figure doesn't show up.

  2. use plt.switch_backend('Agg'), this will switch the backend to 'agg' and no figure printed on the screen.

3
Have you tried just using plt.savefig? Without trying to change the backend.Andras Deak
Yes, my first try is just using plt.savefig. When the script is finish, all the graphs show up on the screen.Yiming REN
Showing up is fine. But was the figure saved? If this is your problem: use plt.close afterwards to close it.Andras Deak
plt.close works !!! :) thanksYiming REN

3 Answers

5
votes

You can try to switch the backend. Apparently Spyder loads matplotlib before you do, and use has no effect. This may be helpful: How to switch backends in matplotlib / Python

5
votes

The answer to your original question is simple. If you don't want to show the graph on screen, just don't use plt.show() So what you've gotta do is simply:

import matplotlib.pylab as plt    
plt.plot(x,y) #whatever the x, y data be
#plt.show()  """Important: either comment this line or delete it"""
plt.savefig('path/where/you/want/to/save/filename.ext') 
#'filename' is either a new file or an already existing one which will get overwritten at the time of execution. 'ext' can be any valid image format including jpg, png, pdf, etc.
2
votes

plt.plot(x,y) plt.savefig('path/figure_filename.jpg',dpi=300)