I found that using matplotlib just to draw a diagram into a file is not as easy as it seems from reading the tutorials.
In the tutorials it is explained, that you just accumulate the 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. That also works fine if you just execute it as a shell. But if you give this code to a process that doesn’t have any window (like jenkins), then you just 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, as I understand the sourcecode around the stack-trace lines, is that backend_tkagg.py expects to use an existing window (see the Tk.Tk() line in the stacktrace). So I wonder if there is a way to draw diagrams with matplotlib (or python at all) without relying on a window(-manager) to do the work.
You need to set a backend which will write directly to a file.
For details, see :
http://matplotlib.sourceforge.net/faq/usage_faq.html#what-is-a-backend
You need to call matplotlib.use before importing pyplot.
For instance :
Actually, I just found out that this is also the solution given in the documentation :
http://matplotlib.sourceforge.net/faq/howto_faq.html#generate-images-without-having-a-window-appear