Draw and write image file without window

I found that using matplotlib just to draw a diagram into a file is not as simple as it seems from reading tutorials. The tutorials explain that you simply accumulate data, and then:

 import matplotlib.pyplot as plt # ... fill variables with meaningful stuff plt.plot(data.x,data.y,format_string) plt.savefig(filename) 

And done. This also works great if you just execute it as a shell. But if you pass this code to a process that has no window (e.g. jenkins), then you will only get the following error:

 Traceback (most recent call last): File "./to_graph.py", line 89, in <module> main() File "./to_graph.py", line 78, in main plt.plot(warnings[0],warnings[1],args.format_warnings,label="Warnings") File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2460, in plot ax = gca() File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 701, in gca ax = gcf().gca(**kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 369, in gcf return figure() 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 

The reason for this error, since I understand the source code around the stack trace lines, is because backend_tkagg.py expects to use an existing window (see the Tk.Tk () line in stacktrace). So I wonder if there is a way to draw diagrams with matplotlib (or python in general) without relying on a window (-manager) to get the job done.

+4
source share
2 answers

You need to install the backend, which will be written directly to the file.

See http://matplotlib.sourceforge.net/faq/usage_faq.html#what-is-a-backend for details

You need to call matplotlib.use before importing pyplot.

For instance:

 import matplotlib matplotlib.use("AGG") import pyplot # continue as usual 

Actually, I just found out that this is also the solution indicated in the documentation:

http://matplotlib.sourceforge.net/faq/howto_faq.html#generate-images-without-having-a-window-appear

+5
source

Thanks! I also had this problem. Now I can use the images to generate raspberries and save using unused variables in a graphical environment. Here is an example:

pi @ raspberrypi / var / www $ cat testimgpython.py

 import matplotlib matplotlib.use('AGG') import matplotlib.pyplot as plt senial = [2, 3, 5, 8, 20, 50, 100] tiempo = range(len(senial)) plt.plot(tiempo, senial) plt.savefig('/var/www/imageSimple1.png') print 'Hecho!' 
+1
source

All Articles