I'd like to save a pyplot figure into a buffer and then base64 encoded so that I can embed it into a html body later.
def draw_picture():
fig = plt.figure()
plt.plot([1, 2, 3],[3, 4, 5])
buf = BytesIO()
fig.savefig(buf, format="png")
data = base64.b64encode(buf.getvalue()).decode("utf-8")
return "<img src='data:image/png;base64,{data}'/>".format(data=data)
The first problem I met is that it always requires the environment variable $DISPLAY
or I will get this error:
File "/home/mals/bin/chart.py", line 30, in hello
fig = plt.figure()
File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 533, in figure
**kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 161, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/_backend_tk.py", line 1046, in new_figure_manager_given_figure
window = Tk.Tk(className="matplotlib")
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1745, 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 was not trying to show the figure but why it still needs to read $DISPLAY
?
The second problem is the statement fig = plt.figure
takes 20 seconds!