pyplot: no display name and no $DISPLAY environment variable [duplicate] - python

I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
Traceback (most recent call last):
File "graph.py", line 13, in <module>
nx.draw(G)
File "/usr/lib/pymodules/python2.5/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I get a different error now:
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
matplotlib.use('Agg')
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
File "graph.py", line 15, in <module>
nx.draw(G)
File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I get a different error now:
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
matplotlib.use('Agg')
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
File "graph.py", line 15, in <module>
nx.draw(G)
File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

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

Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
>>> import matplotlib>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
Then modify the backend in that file to backend : Agg. That is it.

The clean answer is to take a little bit of time correctly prepare your execution environment.
The first technique you have to prepare your execution environment is to use a matplotlibrc file, as wisely recommended by Chris Q., setting
backend : Agg
in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc file.
The second technique you have to prepare your execution environment is to use the MPLBACKEND environment variable (and inform your users to make use of it):
export MPLBACKEND="agg"
python <program_using_matplotlib.py>
This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.
Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.

I got the error while using matplotlib through Spark. matplotlib.use('Agg') doesn't work for me. In the end, the following code works for me. More here
import matplotlib.pyplot as plt.
plt.switch_backend('agg')

I will just repeat what #Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.
import matplotlib
matplotlib.use('Agg')
Or one would get error
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*
This will resolve all Display issue

I found this snippet to work well when switching between X and no-X environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt

When signing into the server to execute the code
use this instead:
ssh -X username#servername
the -X will get rid of the no display name and no $DISPLAY environment variable
error
:)

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
It works for me.

What system are you on? It looks like you have a system with X11, but the DISPLAY environment variable was not properly set. Try executing the following command and then rerunning your program:
export DISPLAY=localhost:0

One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user#debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root#debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root#debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:
import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
matplotlib.use('Agg')
# now import other things from matplotlib
import matplotlib.pyplot as plt
Credit: https://stackoverflow.com/a/45756291/207661

For Google Cloud Machine Learning Engine:
import matplotlib as mpl
mpl.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
And then to print to file:
#PDF build and save
def multi_page(filename, figs=None, dpi=200):
pp = PdfPages(filename)
if figs is None:
figs = [mpl.pyplot.figure(n) for n in mpl.pyplot.get_fignums()]
for fig in figs:
fig.savefig(pp, format='pdf', bbox_inches='tight', fig_size=(10, 8))
pp.close()
and to create the PDF:
multi_page(report_name)

import matplotlib
matplotlib.use('Agg')
worked for me as long as I was calling the plotting functions/code directly. But if you are using
from joblib import Parallel, delayed
Parallel and delayed modules for parallelizing your code then you need to add
matplotlib.rcParams.update({'backend': 'Agg'})
line inside your function in order for agg backend to work.

Related

Can't use pyplot due to _tkinter.TclError: unknown color name

I've got a simple code:
from matplotlib import pyplot as plt
plt.plot([1,2,5])
plt.show()
It works fine in jupyter notebook, however when I try to run it using command line:
$ python3 main.py
It throws an error:
_tkinter.TclError: unknown color name "[97]#282a36"
The whole trackeback:
Traceback (most recent call last):
File "main.py", line 2, in <module>
plt.plot([1,2,5])
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2811, in plot
return gca().plot(
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 935, in gca
return gcf().gca(**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 525, in figure
**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 3218, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backends/_backend_tk.py", line 1008, in new_figure_manager_given_figure
window = Tk.Tk(className="matplotlib")
File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: unknown color name "[97]#282a36"
I already tried changing matplotlib's backend:
import matplotlib
matplotlib.use('pdf') # Or using other arguments matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,5])
plt.show()
It gives me the same error message.
I also tried installing matplotlib using pip and my distribution package manager, both giving me the same error.
tkinter has been installed from my distribution repositories.
Any suggest would be helpful, I couldn't find any solution on similar questions.
After reading this issue on matplotlib's Github page, I emptied out my .Xresources and it fixed the issue.
So I looked a little bit more into the .Xresources file and I found out a line:
*background: [97]#282a36
Which was the cause of matplotlib complaining about a color nameed: [97]#282a36:
_tkinter.TclError: unknown color name "[97]#282a36"
Removing [97] from the line fixed the issue. remember that you have to run:
xrdb -merge .Xresources
To make the changes take place.

Not able to import matplotlib in Google Flexible App engine with flask and python 3.6 [duplicate]

I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
Traceback (most recent call last):
File "graph.py", line 13, in <module>
nx.draw(G)
File "/usr/lib/pymodules/python2.5/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I get a different error now:
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
matplotlib.use('Agg')
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
File "graph.py", line 15, in <module>
nx.draw(G)
File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I get a different error now:
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
matplotlib.use('Agg')
G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")
/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
File "graph.py", line 15, in <module>
nx.draw(G)
File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
cf=pylab.gcf()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
return figure()
File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
**kwargs)
File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
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
Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
>>> import matplotlib>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
Then modify the backend in that file to backend : Agg. That is it.
The clean answer is to take a little bit of time correctly prepare your execution environment.
The first technique you have to prepare your execution environment is to use a matplotlibrc file, as wisely recommended by Chris Q., setting
backend : Agg
in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc file.
The second technique you have to prepare your execution environment is to use the MPLBACKEND environment variable (and inform your users to make use of it):
export MPLBACKEND="agg"
python <program_using_matplotlib.py>
This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.
Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.
I got the error while using matplotlib through Spark. matplotlib.use('Agg') doesn't work for me. In the end, the following code works for me. More here
import matplotlib.pyplot as plt.
plt.switch_backend('agg')
I will just repeat what #Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.
import matplotlib
matplotlib.use('Agg')
Or one would get error
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*
This will resolve all Display issue
I found this snippet to work well when switching between X and no-X environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
When signing into the server to execute the code
use this instead:
ssh -X username#servername
the -X will get rid of the no display name and no $DISPLAY environment variable
error
:)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
It works for me.
What system are you on? It looks like you have a system with X11, but the DISPLAY environment variable was not properly set. Try executing the following command and then rerunning your program:
export DISPLAY=localhost:0
One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user#debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root#debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root#debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su
To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:
import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if os.name == 'posix' and "DISPLAY" not in os.environ:
matplotlib.use('Agg')
# now import other things from matplotlib
import matplotlib.pyplot as plt
Credit: https://stackoverflow.com/a/45756291/207661
For Google Cloud Machine Learning Engine:
import matplotlib as mpl
mpl.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
And then to print to file:
#PDF build and save
def multi_page(filename, figs=None, dpi=200):
pp = PdfPages(filename)
if figs is None:
figs = [mpl.pyplot.figure(n) for n in mpl.pyplot.get_fignums()]
for fig in figs:
fig.savefig(pp, format='pdf', bbox_inches='tight', fig_size=(10, 8))
pp.close()
and to create the PDF:
multi_page(report_name)
import matplotlib
matplotlib.use('Agg')
worked for me as long as I was calling the plotting functions/code directly. But if you are using
from joblib import Parallel, delayed
Parallel and delayed modules for parallelizing your code then you need to add
matplotlib.rcParams.update({'backend': 'Agg'})
line inside your function in order for agg backend to work.

Matplotlib graph not showing

My project requires me to open Raspberry Pi's terminal using putty and Connectify hotspot on my Windows System to plot and show the graph. However , the graph was only able to be shown on my Raspberry Pi monitor but not my Window's one. Here's the code that i used :
import pymysql
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
conn = pymysql.connect(host="localhost", user="root", passwd="123456", db="XXX")
cur = conn.cursor()
query = """
SELECT data,time
FROM sensordata
WHERE time >= "2017-05-21"
AND time < "2017-05-23"
"""
cur.execute(query)
data = cur.fetchall()
cur.close()
conn.close()
time,data= zip(*data)
plt.plot(data,time)
plt.title("XXX ")
plt.xlabel("Time & Date ")
plt.ylabel("Strength")
fig = plt.gcf()
fig.set_size_inches (55,27.5)
plt.grid(True)
plt.draw()
fig.savefig('test.png' ,dpi=100)
plt.show()
The error i received when i tried to run it on the putty terminal is :
Traceback (most recent call last):
File "matplot2.py", line 27, in <module>
plt.plot(data,time)
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3092, in plot
ax = gca()
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 828, in gca
ax = gcf().gca(**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 462, in gcf
return figure()
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1813, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I've tried using both matplotlib.use('Agg') and matplotlib.use('TKAgg') from some solutions i read but it did not solve my issue. Hope that someone would be able to solve my issue so that i can display the graph on my Window's monitor ... Thanks in advance
The error '_tkinter.TclError: no display name and no $DISPLAY environment variable' suggests that there is a problem with your X11 server.
I do not know from which host you ssh on your Raspberry, but you must run an X-Server on Windows (such as VcXsrv ). Then make sure to allow X11 forwarding, e.g. ssh -X or even ssh -Y. When using putty make sure to set Enable X11 forwarding under Connection -> SSH -> X11.
If all is set up, running the matplotlib bar chart demo (see comments) should look like this:
enter image description here
(no image since someone downvoted the answer for whatever reason)
If your problem persists, you could try to use MobaXTerm (on Windows) which comes with an X Server and should work out of the box.
If you are running VcXSrv, for me I have to export my $DISPLAY variable by running the following code in your shell: export DISPLAY=localhost:0.0

RuntimeError: Invalid DISPLAY variable

I am running my python script in another machine by using ssh command in linux. I have also run this command :
source ~/.bashrc
after logging in the other machine, in order to define the proper paths in the new machine. I was getting the error message for running the following python code lines even I have tried to follow the instruction in this question by defining the backend.
>>> import matplotlib
>>> import pylab as plt
>>> matplotlib.use('Agg')
>>> import numpy as np
>>> x=np.arange(0,2,0.001)
>>> y=np.sin(x)**2+4*np.cos(x)
>>> fig = plt.figure()
>>> plt.plot(x,y,'r.')
The error message
This probably means that Tcl wasn't installed properly.
Traceback (most recent call last):
File "Systematic_Optimised.py", line 513, in <module>
fig = plt.figure()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/vol/aibn84/data2/zahra/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
any suggestion how to fix the problem
You must declare matplotlib.use('agg') before import pylab as plt.
Reference
Add
plt.switch_backend('agg')
after
import matplotlib.pyplot as plt

Plotting error python in linux environment pandas...possible to just save? [duplicate]

This question already has answers here:
Generating matplotlib graphs without a running X server [duplicate]
(2 answers)
Closed 8 years ago.
I am trying to plot a pandas series in python. However, rather than working from my home computer I am working via grid computing on a linux shell. When I type:
series.plot()
I get this error:
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pandas-0.15.0-py2.7-linux-x86_64.egg/pandas/tools/plotting.py", line 2487, in plot_series
**kwds)
File "/usr/local/lib/python2.7/dist-packages/pandas-0.15.0-py2.7-linux-x86_64.egg/pandas/tools/plotting.py", line 2293, in _plot
plot_obj.generate()
File "/usr/local/lib/python2.7/dist-packages/pandas-0.15.0-py2.7-linux-x86_64.egg/pandas/tools/plotting.py", line 919, in generate
self._setup_subplots()
File "/usr/local/lib/python2.7/dist-packages/pandas-0.15.0-py2.7-linux-x86_64.egg/pandas/tools/plotting.py", line 952, in _setup_subplots
fig = self.plt.figure(figsize=self.figsize)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
**kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
Does anyone know what I can do or what I should ask my sys admin to do? Is it possible to just save the plot to a file without having it in some sort of display environment first?
You could reset the matplotib backend to one that does not require a display, such as AGG, PNG, SVG, PDF, PS, Cairo, or GDK:
import numpy as np
import pandas as pd
def reset_backend(backend):
import sys
del sys.modules['matplotlib.backends']
del sys.modules['matplotlib.pyplot']
import matplotlib as mpl
mpl.use(backend) # do this before importing pyplot
import matplotlib.pyplot as plt
return plt
reset_backend('agg')
ser = pd.Series(np.random.random(5))
ser.plot()
plt.savefig('/path/to/file.png')
Note that what backends you have available depends on how your installation of matplotlib was built. If you call reset_backend with a backend that is not available, you will see an error message which lists the backends which are available on your installation.

Categories

Resources