Skip to content

Instantly share code, notes, and snippets.

@liuyxpp
Forked from wilsaj/flaskplotlib.py
Created September 29, 2011 09:33
Show Gist options
  • Save liuyxpp/1250396 to your computer and use it in GitHub Desktop.
Save liuyxpp/1250396 to your computer and use it in GitHub Desktop.
Example of rendering a matplotlib image directly to Flask view
from flask import Flask, make_response, render_template
app = Flask(__name__)
@app.route("/")
def index():
render_template("index.html")
@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()
{% extends "layout.html" %}
{% block body %}
<h1>Render a Image Directly by matplotlib</h1>
<img src="{{ url_for('simple') }}" alt="loading..." />
{% endblock %}
@liuyxpp
Copy link
Author

liuyxpp commented Sep 29, 2011

Demonstrate how to embedded the rendered image in other webpage other than in a single webpage.

@jgscode2012
Copy link

I'm totally new to Web Programming, but it seems that this code is not going to work. I kept getting Internal Server Error from it.

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