将matplotlib图传递给HTML(烧瓶)

Ale*_*ley 26 html python image matplotlib flask

我正在使用matplotlib在Web应用程序中呈现一些图形.我以前fig.savefig()在运行脚本时使用过.但是,我需要一个函数来返回一个实际的".png"图像,以便我可以用我的HTML调用它.

一些(可能不必要的)信息:我正在使用Python Flask.我想我可以使用fig.savefig()并将图形粘贴在我的静态文件夹中,然后从我的HTML中调用它,但我不想每次都这样做.如果我可以创建图形,从中创建图像,返回该图像,并从我的HTML中调用它,那么它将是最佳的,然后它就会消失.

创建图形的代码有效.但是,它会返回一个数字,我想这与HTML不兼容.

这是我draw_polygon在路由中调用的地方,draw_polygon是返回图形的方法:

@app.route('/images/<cropzonekey>')
def images(cropzonekey):
    fig = draw_polygons(cropzonekey)
    return render_template("images.html", title=cropzonekey, figure = fig)
Run Code Online (Sandbox Code Playgroud)

这是我试图生成图像的HTML.

<html>
  <head>
    <title>{{ title }} - image</title>
  </head>
  <body>
    <img src={{ figure }} alt="Image Placeholder" height="100">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

并且,正如你可能猜到的,当我加载页面时,我得到的只是Image Placeholder.所以,他们不喜欢我用这个数字输入的格式.

有谁知道matplotlib方法/ work-arounds将图形变成实际图像?我到处都是这些文档,但我找不到任何东西.谢谢!

顺便说一句:不认为有必要包含构成数字的python代码,但如果你们需要看到它(我只是不想混淆问题),我可以包括它

Mig*_*uel 31

您必须将HTML和图像分成两个不同的路径.

您的/images/<cropzonekey>路线将仅为该页面提供服务,并且该页面的HTML内容中将引用第二条路线,即提供图像的路线.

图像从您生成的内存文件以其自己的路径提供savefig().

我显然没有对此进行测试,但我相信以下示例将按原样运行,或者让您非常接近工作解决方案:

@app.route('/images/<cropzonekey>')
def images(cropzonekey):
    return render_template("images.html", title=cropzonekey)

@app.route('/fig/<cropzonekey>')
def fig(cropzonekey):
    fig = draw_polygons(cropzonekey)
    img = StringIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')
Run Code Online (Sandbox Code Playgroud)

您的images.html模板变为:

<html>
  <head>
    <title>{{ title }} - image</title>
  </head>
  <body>
    <img src="{{ url_for('fig', cropzonekey = title) }}" alt="Image Placeholder" height="100">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • Miguel,首先,只想说你的烧瓶教程是完全惊人的.+1就是为了那个.但是,当我导航到该页面时,我仍然收到占位符文本.这可能是一个与烧瓶无关的问题(即`draw_polygons(cropzonekey)`返回的格式? (4认同)

Tim*_*eed 5

对于Python3 ....

我有一个DataFrame,我想在Flask中显示此图。

因此,创建该图的Base64映像。

    df_week_min_az = pd.DataFrame.from_dict(week_max_az.to_dict(),
                                            orient='index', columns=['min_az'])



    sunalt = df_week_max_angle.plot().get_figure()
    buf = io.BytesIO()
    sunalt.savefig(buf, format='png')
    buf.seek(0)
    buffer = b''.join(buf)
    b2 = base64.b64encode(buffer)
    sunalt2=b2.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

我现在使用这样的base64编码数据来调用我的模板。

return render_template('where.html', form=form, sunalt=sunalt2)

模板的相关部分(即图片位)如下所示。

 {% if sunalt != None %}

      <h2>Sun Altitude during the year</h2>
    <img src="data:image/png;base64,{{ sunalt }}">
{% endif %}
Run Code Online (Sandbox Code Playgroud)

希望能对某人有所帮助。


akk*_*hil 5

蟒蛇 3

我遇到了很多错误,比如 - Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!

对于所有想要在 Flask 中使用 matplotlib 并在 python 3 的 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.route('/plot')
    def plot():
        img = BytesIO()
        y = [1,2,3,4,5]
        x = [0,2,1,3,4]

        plt.plot(x,y)

        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)
Run Code Online (Sandbox Code Playgroud)

flaskr/templates/plot.html

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

Run Code Online (Sandbox Code Playgroud)