Skip to content

Instantly share code, notes, and snippets.

@tebeka
Created April 20, 2013 14:43
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save tebeka/5426211 to your computer and use it in GitHub Desktop.
Save tebeka/5426211 to your computer and use it in GitHub Desktop.
Serving dynamic images with Pandas and matplotlib (using flask)
#!/usr/bin/env python2
'''Serving dynamic images with Pandas and matplotlib (using flask).'''
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from cStringIO import StringIO
import base64
from flask import Flask
app = Flask(__name__)
html = '''
<html>
<body>
<img src="data:image/png;base64,{}" />
</body>
</html>
'''
@app.route("/")
def hello():
df = pd.DataFrame(
{'y':np.random.randn(10), 'z':np.random.randn(10)},
index=pd.period_range('1-2000',periods=10),
)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
df.plot(ax=ax)
io = StringIO()
fig.savefig(io, format='png')
data = base64.encodestring(io.getvalue())
return html.format(data)
if __name__ == '__main__':
app.run()
@prakashsharma91
Copy link

TypeError: string argument expected, got 'bytes'

@christianversloot
Copy link

christianversloot commented Nov 29, 2018

@prakashsharma91 This happens because you provide input of type bytes to StringIO, which is meant for String I/O only.
You can make it work by replacing StringIO with BytesIO. You'll then simply have to convert the byte string to a real string and you're good to go. Small example:

io = BytesIO()
fig.savefig(io, format='png')
data = base64.encodestring(io.getvalue()).decode('utf-8')
html = 'data:image/png;base64,{}';
return html.format(data);

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