Created
April 21, 2013 15:24
-
-
Save tebeka/5429980 to your computer and use it in GitHub Desktop.
Two figures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
'''Serving dynamic images with matplotlib (using flask).''' | |
# No windows should pop up in a web server | |
import matplotlib | |
matplotlib.use('Agg') | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from cStringIO import StringIO | |
from flask import Flask | |
app = Flask(__name__) | |
# HTML template, we embed base64 encoded image data in the <img> HTML element | |
html = ''' | |
<html> | |
<body> | |
<img src="data:image/png;base64,{}" /> | |
<img src="data:image/png;base64,{}" /> | |
</body> | |
</html> | |
''' | |
def img(xs, ys, label): | |
fig = plt.figure(figsize=(8,3)) | |
ax = fig.add_subplot(1, 1, 1) | |
ax.plot(xs, ys, label=label) | |
ax.legend() | |
io = StringIO() | |
fig.savefig(io, format='png') | |
return io.getvalue().encode('base64') | |
@app.route("/") | |
def index(): | |
xs = np.linspace(-10, 10, 1000) | |
return html.format( | |
img(xs, np.sin(xs), 'sin(x)'), | |
img(xs, np.log(xs), 'log(x)') | |
) | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment