Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Plot a PNG using matplotlib in a web request, using Flask.
"Plot a PNG using matplotlib in a web request, using Flask."
# Install dependencies, preferably in a virtualenv:
# pip install flask matplotlib
# Run the development server:
# python
# Go to http://localhost:5000/plot.png and see a plot of random data.
import random
import StringIO
from flask import Flask, make_response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
app = Flask(__name__)
def plot():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
xs = range(100)
ys = [random.randint(1, 50) for x in xs]
axis.plot(xs, ys)
canvas = FigureCanvas(fig)
output = StringIO.StringIO()
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
if __name__ == '__main__':
sburns commented Apr 3, 2014

exactly what I needed, thank you.


i like it, thx!!!



mapfumo commented Sep 6, 2015

Awesome. Thank you.

smargs commented Oct 29, 2015

Hi, thank you for the code. I ran it and got this msg '* Restarting with stat'. So i installed watchdog suggested in this post and now I get this '* '*Restarting with windowsapi reloader'. And the localhost page doesn't work (keeps loading). Would you know how to make this work ? Thank you.


Is there a way to embed this into a flask template? Right now i'm passing the response variable into an html template using the render_template function, but the image is not showing up; instead, only the response string is rendering. Thank you in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.