简单matplotlib作为flask生成的网页中的嵌入图像

简单matplotlib作为flask生成的网页中的嵌入图像,matplotlib,flask,Matplotlib,Flask,我正在研究这个例子 我只是不知道如何使用flask或matplot库作为网页或图像返回 @app.route('/visualize') def visualize(): a_dictionary = {"a": 1, "b": 2, "c": 3} keys = a_dictionary.keys() values = a_dictionary.values() plt.bar(keys, valu

我正在研究这个例子

我只是不知道如何使用flask或matplot库作为网页或图像返回

@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')
我正在尝试将这样的结果嵌入到html页面中

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

我对如何将互联网上的其他作品应用到这个案例中感到困惑。对于导入哪些模块,似乎有不同的解决方案,有些使用seaborn


有人能帮忙吗?

这里可以找到最清晰的解释解决方案 因此,我修改了上面的代码,该代码从字典构建matplotlib图,下面我将展示如何将其传递到html页面

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()
在templates文件夹中

模板/plot.html

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

热图-
热图

这里可以找到最清晰的解释解决方案 因此,我修改了上面的代码,该代码从字典构建matplotlib图,下面我将展示如何将其传递到html页面

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()
在templates文件夹中

模板/plot.html

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

热图-
热图