简体   繁体   中英

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)
    return render_template('devices/test.html', plot_url=plot_url)

test.html

<div class="container">
      <h2>Image</h2>    
      <img src= {{ resized_img_src('plot_url') }} class="img-rounded" alt="aqui" width="304" height="236"> 
    </div>

Im trying to use seaborn with this, but even with matplolib I couldn't get any result.

Note: I don't want to save image and load it after.

With matplotlib you can do:

#Add this imports
import StringIO
import base64

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

    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:

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

If you want to use seaborn , you just need to import seaborn and set the styles you want, eg

...
import seaborn as sns
...

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

    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)

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.16
from cStringIO import StringIO
import base64

@devices_blueprint.route('/devices/test/')
def test():
    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM