Skip to content

Instantly share code, notes, and snippets.

@michaelfeng
Forked from tebeka/gist:5426211
Created November 21, 2017 10:27
Show Gist options
  • Save michaelfeng/5282469491a7d38f9cd635d7a7c0fbbd to your computer and use it in GitHub Desktop.
Save michaelfeng/5282469491a7d38f9cd635d7a7c0fbbd to your computer and use it in GitHub Desktop.

Revisions

  1. @tebeka tebeka created this gist Apr 20, 2013.
    42 changes: 42 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    #!/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()