Generating a PNG with matplotlib when DISPLAY is undefined

Asked 1 years ago, Updated 1 years ago, 115 views

You are about to use NetworkX on Python. This error occurs when you run the program below. Is there anything I missed?

#!/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

graph matplotlib python

2022-09-22 21:31

1 Answers

The problem is that matplotlib uses the x-based Beckend as the default. I had the same problem with my server. The solution I used is to add the code below before other pylab/matplotlib/pyplot modules are imported.

import matplotlib
# # Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')

Another option is to set it to .matplotlibc.


2022-09-22 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.