Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example of rendering a matplotlib image directly to Flask view
from flask import Flask, make_response
app = Flask(__name__)
@app.route("/simple.png")
def simple():
import datetime
import StringIO
import random
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
fig=Figure()
ax=fig.add_subplot(111)
x=[]
y=[]
now=datetime.datetime.now()
delta=datetime.timedelta(days=1)
for i in range(10):
x.append(now)
now+=delta
y.append(random.randint(0, 1000))
ax.plot_date(x, y, '-')
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
png_output = StringIO.StringIO()
canvas.print_png(png_output)
response=make_response(png_output.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
if __name__ == "__main__":
app.run()
@jyoo

This comment has been minimized.

Show comment Hide comment
@jyoo

jyoo Jan 18, 2012

Yo this is awesome. Thank you and works perfectly out of the box.

jyoo commented Jan 18, 2012

Yo this is awesome. Thank you and works perfectly out of the box.

@Wayn0

This comment has been minimized.

Show comment Hide comment
@Wayn0

Wayn0 Nov 20, 2013

Thanks, this has given me some ideas!

Wayn0 commented Nov 20, 2013

Thanks, this has given me some ideas!

@dledgerton

This comment has been minimized.

Show comment Hide comment
@dledgerton

dledgerton Dec 6, 2014

Thanks! I teaching my stats class using Python and this is very helpful.

Thanks! I teaching my stats class using Python and this is very helpful.

@taylorhawks

This comment has been minimized.

Show comment Hide comment
@taylorhawks

taylorhawks Nov 19, 2015

Just what I was looking for. Thanks!

Just what I was looking for. Thanks!

@crystal95

This comment has been minimized.

Show comment Hide comment
@crystal95

crystal95 Mar 17, 2016

I have a problem that when render matplot image directly into flask view , I loose my basic features of matplot image(like now it donot show coordinates when hovering over the image ,now I cannot zoom into a particular portion of image etc ) . Can you suggest how can I render matplotimage into flask and still having these features of images ? (I am able to do that using pygal but not matplot lib)
Thanks in advance :)

I have a problem that when render matplot image directly into flask view , I loose my basic features of matplot image(like now it donot show coordinates when hovering over the image ,now I cannot zoom into a particular portion of image etc ) . Can you suggest how can I render matplotimage into flask and still having these features of images ? (I am able to do that using pygal but not matplot lib)
Thanks in advance :)

@ivorscott

This comment has been minimized.

Show comment Hide comment
@ivorscott

ivorscott May 16, 2016

Thanks Andy. :)

Thanks Andy. :)

@aryeguetta

This comment has been minimized.

Show comment Hide comment
@aryeguetta

aryeguetta Sep 24, 2016

Great! thanks that works wonderfully.
Is there a way that I can do something like that and using Drawnow() and plotting a PNG image that will show my graph and also interactive mode.
I was trying to figure that ourt and I am getting always Error with $DISPLAY.
Thanks.

Great! thanks that works wonderfully.
Is there a way that I can do something like that and using Drawnow() and plotting a PNG image that will show my graph and also interactive mode.
I was trying to figure that ourt and I am getting always Error with $DISPLAY.
Thanks.

@kwanwasutumkethom

This comment has been minimized.

Show comment Hide comment
@kwanwasutumkethom

kwanwasutumkethom Dec 14, 2016

thanks !

thanks !

@tacaswell

This comment has been minimized.

Show comment Hide comment
@tacaswell

tacaswell Jan 25, 2017

Patch to make this work with python 3

15:18 $ diff -u /tmp/fa2.py /tmp/fa.py 
--- /tmp/fa2.py	2017-01-25 15:18:03.000000000 -0500
+++ /tmp/fa.py	2017-01-25 15:13:33.000000000 -0500
@@ -5,7 +5,7 @@
 @app.route("/simple.png")
 def simple():
     import datetime
-    import StringIO
+    from io import BytesIO
     import random
 
     from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
@@ -26,7 +26,7 @@
     ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
     fig.autofmt_xdate()
     canvas=FigureCanvas(fig)
-    png_output = StringIO.StringIO()
+    png_output = BytesIO()
     canvas.print_png(png_output)
     response=make_response(png_output.getvalue())
     response.headers['Content-Type'] = 'image/png'

Patch to make this work with python 3

15:18 $ diff -u /tmp/fa2.py /tmp/fa.py 
--- /tmp/fa2.py	2017-01-25 15:18:03.000000000 -0500
+++ /tmp/fa.py	2017-01-25 15:13:33.000000000 -0500
@@ -5,7 +5,7 @@
 @app.route("/simple.png")
 def simple():
     import datetime
-    import StringIO
+    from io import BytesIO
     import random
 
     from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
@@ -26,7 +26,7 @@
     ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
     fig.autofmt_xdate()
     canvas=FigureCanvas(fig)
-    png_output = StringIO.StringIO()
+    png_output = BytesIO()
     canvas.print_png(png_output)
     response=make_response(png_output.getvalue())
     response.headers['Content-Type'] = 'image/png'
@saikiran6

This comment has been minimized.

Show comment Hide comment
@saikiran6

saikiran6 Feb 19, 2017

Hi Thanks for the example. What is I want to put he result back to same home url. What changes I have to do?

Hi Thanks for the example. What is I want to put he result back to same home url. What changes I have to do?

@saqlain5544

This comment has been minimized.

Show comment Hide comment
@saqlain5544

saqlain5544 Sep 26, 2017

This is a good example but what if i wanted to show this image in my Html <img> tag dynamically without downloading it. I mean within my Markup.

This is a good example but what if i wanted to show this image in my Html <img> tag dynamically without downloading it. I mean within my Markup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment