Skip to content Skip to sidebar Skip to footer

How To Render And Return Plot To View In Flask?

How do I render a plot to the view in flask? devices.py: @devices_blueprint.route('/devices/test/') def test(): y = [1,2,3,4,5] x = [0,2,1,3,4] plot_url = plt.plot(x,y

Solution 1:

With matplotlib you can do:

#Add this importsimport StringIO
import base64

@devices_blueprint.route('/devices/test/')deftest():

    img = StringIO.StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)

In your Html put:

<imgsrc="data:image/png;base64, {{ plot_url }}">

If you want to use seaborn, you just need to import seaborn and set the styles you want, e.g.

...
import seaborn as sns
...

@devices_blueprint.route('/devices/test/')deftest():

    img = StringIO.StringIO()
    sns.set_style("dark") #E.G.

    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)

Solution 2:

I was getting an "Assetion failed" error trying to send the plot using anaconda(python 2.7) on macOS. I managed to fix the bug by explicitly closing plt before returning. Thanks for this piece of code!

#Imports for Python 2.7.16from cStringIO import StringIO
import base64

@devices_blueprint.route('/devices/test/')deftest():
    img = StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)

Post a Comment for "How To Render And Return Plot To View In Flask?"