【问题标题】:simple matplotlib as embedded image in web page generated by flask简单的matplotlib作为flask生成的网页中的嵌入图像
【发布时间】:2021-04-01 18:28:51
【问题描述】:

我正在研究这个例子https://www.kite.com/python/answers/how-to-plot-a-bar-chart-using-a-dictionary-in-matplotlib-in-python

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

@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 flask


    【解决方案1】:

    可以在这里找到最清晰的解释解决方案 Passing a matplotlib figure to HTML (flask) 所以我已经修改了上面的代码,它从字典中构建了一个 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()
    

    在模板文件夹中

    模板/plot.html

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

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多