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:
just use
plt.close()
, this will not change the backend and the figure doesn't show up.use
plt.switch_backend('Agg')
, this will switch the backend to 'agg' and no figure printed on the screen.
plt.savefig
? Without trying to change the backend. – Andras Deakplt.close
afterwards to close it. – Andras Deak