Yiming REN
Yiming REN

Reputation: 63

Can't use matplotlib.use('Agg'), graphs always show on the screen

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.

Upvotes: 5

Views: 26659

Answers (3)

Parth Naik
Parth Naik

Reputation: 51

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.

Upvotes: 5

aerijman
aerijman

Reputation: 2782

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

Upvotes: 1

user1620443
user1620443

Reputation: 794

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

Upvotes: 5

Related Questions