Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic plots to display on Flask?

Tags:

python

io

flask

I wish to create dynamic plots based on user input on a flask app. However I am getting the following error: string argument expected, got 'bytes'

If I use io.BytesIO(), I am not getting this error, but I am not getting the plot on test.html

from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import io
import base64

app = Flask(__name__)

@app.route('/plot')
def build_plot():
    img = io.StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())
    return render_template('test.html', plot_url=plot_url)

if __name__ == '__main__':
    app.debug = True
    app.run()

Test.html

<!DOCTYPE html>
<html>
<title> Plot</title>
<body>
<img src="data:image/png;base64, {{ plot_url }}">
</body>
</html>
like image 474
RRC Avatar asked Jan 04 '17 08:01

RRC


People also ask

How do you plot a dynamic graph in Python?

Make a list of data points and colors. Plot the bars with data and colors, using bar() method. Using FuncAnimation() class, make an animation by repeatedly calling a function, animation, that sets the height of the bar and facecolor of the bars. To display the figure, use show() method.

Is flask dynamic or static?

Flask automatically creates a static view that serves static files from a folder named static in your application's directory. You can also use the url_for() method to allow for more dynamic URLs. Its use reduces the amount of modification needed in the code if something needs to change in your URL references.


1 Answers

Use BytesIO and later decode()

Working example

from flask import Flask
#from flask import render_template
import matplotlib.pyplot as plt
import io
import base64

app = Flask(__name__)

@app.route('/plot')
def build_plot():

    img = io.BytesIO()

    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

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

    return '<img src="data:image/png;base64,{}">'.format(plot_url)

if __name__ == '__main__':
    app.debug = True
    app.run()
like image 53
furas Avatar answered Sep 28 '22 04:09

furas