How to pass rendered plot to a html file through render_template? How to pass rendered plot to a html file through render_template? flask flask

How to pass rendered plot to a html file through render_template?


First of all, pay enough attention to your html file name, I see two different names, hello.html and home.html. Then try to use matplotlib.backends.backend_agg as follows:

from base64 import b64encodefrom io import BytesIOfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas@app.route('/')def build_Plot():    output = io.BytesIO()    y = [1, 2, 3, 4, 5]    x = [0, 2, 1, 3, 4]    plt.plot(x, y)    f = plt.figure()    canvas = FigureCanvas(f)    canvas.print_png(output)    plot_data= b64encode(output.getvalue()).decode('ascii')    output.seek(0)    return render_template("home.html", url=plot_data)

In this way, it has the canvas write to an in-memory file, and the resulting PNG data is then encoded to base64 and interpolated in a data URL.


plot_url actually stores is an URL to an image. So if you already have a HTML page like hello.html, you can do this while rendering it:

hello.html:

<!doctype html><html>    <head>        <meta charset="UTF-8">        <title>MyFlaskApp</title>    </head>    <body>        {% block body %}            {% if plot %}                <img src="data:image/png;base64,{{url}}">            {% endif %}        {% endblock %}    </body></html>

In the Python file, you can do the below:

return render_template("hello.html",plot=True, url=plot_url) 

Note the plot_url comes from the base64.b64encode(img.getvalue()).decode() line mentioned in the answer you've linked.


Assuming you mean to be passing the image along with the page (instead of including a url in the img tag, ghe format of data URLs suggests that you need

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

where data is a base64-encoding of a PNG representation of the image.

But if you mean to be passing in a URL, then you'd want something like

<img src="{{ url }}" />

where url is a link back to a view method in your app that will return a non-base64-encoded image.