Christopher
Christopher

Reputation: 617

simple matplotlib as embedded image in web page generated by flask

I am working through this example https://www.kite.com/python/answers/how-to-plot-a-bar-chart-using-a-dictionary-in-matplotlib-in-python

I am just not sure how to use flask or matplot lib to return as a web page or as an image

@app.route('/visualize')
def visualize():


    a_dictionary = {"a": 1, "b": 2, "c": 3}
    keys = a_dictionary.keys()
    values = a_dictionary.values()
    plt.bar(keys, values)
    bytes_image = io.BytesIO()
    plt.savefig('img')

    return send_file(img,mimetype='img')

I am trying to embed the result like this into a html page

<img src="{{ url_for('visualize') }}" alt="Result" style="width:100%">

I am getting confused how to apply other works on the internet into this case. There seem to be different solutions about which modules are imported, some using seaborn.

Can anyone help please?

Upvotes: 3

Views: 1061

Answers (1)

Christopher
Christopher

Reputation: 617

The clearest explain solution can be found here Passing a matplotlib figure to HTML (flask) So I have adapted the code above which builds a matplotlib graph from a dictionary, and below I show how it can be passed to a html page

In the init.py

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from flask import Flask, render_template
from io import BytesIO
import base64


app = Flask(__name__)

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


    img = BytesIO()


    a_dictionary = {"a": 4, "b": 20, "c": 6}
    keys = a_dictionary.keys()
    values = a_dictionary.values()
    plt.bar(keys, values)

    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)
    plot_url = base64.b64encode(img.getvalue()).decode('utf8')

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

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

In the templates folder

templates/plot.html

<!doctype html>
<title>heatmap - </title>
<section>
  <h2>Heatmap</h2>
  <img src="data:image/png;base64, {{ plot_url }}">
</section>

Upvotes: 2

Related Questions