Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
Yiming REN Avatar asked May 20 '17 13:05

Yiming REN


Video Answer


2 Answers

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

like image 196
user1620443 Avatar answered Oct 04 '22 22:10

user1620443


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.
like image 43
Parth Naik Avatar answered Oct 04 '22 22:10

Parth Naik