Generating matplotlib graphs without a running X server
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
E.g.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
Import Matplotlib without a display
You should almost never use from pylab import *
.
Import what you need from numpy
, scipy
and matplotlib
.
On machines without display, you need to use the agg
backend:
You can achieve this by specifying the environmental variable MPLBACKEND
$ MPLBACKEND=Agg python plot.py
Or by importing matplotlib
before importing matplotlib.pyplot
:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1, 2, 1])
plt.savefig('test.pdf')
To make this the default, you can create a file called matplotlibrc
in the current directory or in $HOME/.config/matplotlib
with the following content:
backend: Agg
Or you could enable X-Forwarding, so the plots will pop up on your host machine:
ssh -X user@server
Python Graphing on linux system without xserver
You can use matplotlib
with no X server by setting the backend to Agg
, PS
, PDF
or SVG
, Cairo
or GDK
(depending on what kind of file you wish to create). You can set the backend in your matplotlibrc
file, which, depending on your installation, may be in a directory such as ~/
or ~/.matplotlib
or ~/.config/matplotlib/
.
Alternatively, you can set the backend in the script itself.
Be sure to set the backend first, before importing other modules such as pyplot
:
import matplotlib
matplotlib.use("Agg")
See this SO question for examples.
Generating a PNG with matplotlib when DISPLAY is undefined
The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read before any other pylab/matplotlib/pyplot import:
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
The alternative is to set it in your .matplotlibrc
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. when plotting figure with pyplot on Pycharm
Solution 1: is to install the GUI backend tk
I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).
All I had to do was to install tkinter
through the Linux bash terminal using the following command:
sudo apt-get install python3-tk
instead of installing it with pip
or directly in the virtual environment in Pycharm.
Solution 2: install any of the matplotlib
supported GUI backends
- solution 1 works fine because you get a GUI backend... in this case the
TkAgg
- however you can also fix the issue by installing any of the matplolib GUI backends like
Qt5Agg
,GTKAgg
,Qt4Agg
, etc- for example
pip install pyqt5
will fix the issue also
- for example
NOTE:
- usually this error appears when you pip install matplotlib and you are trying to display a plot in a GUI window and you do not have a python module for GUI display.
- The authors of
matplotlib
made the pypi software deps not depend on any GUI backend because some people needmatplotlib
without any GUI backend.
Matplotlib: display plot on a remote machine
If you use matplotlib on Mac OS X on the remote machine (B), you must first make sure that you use one of the X11-based display back-ends, since the native Mac OS X back-end cannot export its plots to another display. Selecting a back-end can be achieved with
import matplotlib
matplotlib.use('GTK') # Or any other X11 back-end
The list of supported back-ends can be obtained by giving use()
an incorrect back-end name: matplotlib then prints an error message listing the possible back-ends.
ssh X11 forwarding can then be used to display matplotlib plots.
Automatic detection of display availability with matplotlib
You can detect directly if you have a display with the OS module in python.
in my case it's
>>> import os
>>> os.environ["DISPLAY"]
':0.0'
How to save a figure remotely with pylab?
By default, matplotlib will use something like the TkAgg
backend. This requires an X-server to be running.
While you can just use X-forwarding, there will be a noticeable lag as matplotlib tries to connect with the remote X-server. If you don't need to interact with the plot, it's often nicer to speed things up by avoiding an X-connection entirely.
If you want to make a plot without needing an X-server at all, use the Agg
backend instead.
E.g. do something like this:
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png')
If you want this to be the default behavior, you can modify your matplotlibrc file to use the Agg
backend by default.
See this article for more information.
Related Topics
How to Use a Multiprocessing.Manager()
Differences Between Numpy.Random and Random.Random in Python
Python Numpy/Scipy Curve Fitting
Django Submit Two Different Forms with One Submit Button
Valueerror: Numpy.Dtype Has the Wrong Size, Try Recompiling
Classification Using Movie Review Corpus in Nltk/Python
Making an Asynchronous Task in Flask
Selecting from Multi-Index Pandas
How to Keep Index When Using Pandas Merge
Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:749)
How to Open a File for Exclusive Access in Python
List of Tables, Db Schema, Dump etc Using the Python SQLite3 API
Python Read JSON File and Modify
Typeerror: 'Dict' Object Is Not Callable
Difference Between "Findall" and "Find_All" in Beautifulsoup