将matplotlib图形传递到HTML(烧瓶)

问题描述 投票:27回答:5

我正在使用matplotlib在Web应用程序中渲染某些图形。我在刚运行脚本之前就使用过fig.savefig()。但是,我需要一个函数来返回实际的“ .png”图像,以便可以使用HTML对其进行调用。

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

创建图形的代码起作用。但是,它返回一个数字,我猜这不适用于HTML。

在这里我在路由中称呼draw_polygondraw_polygon是返回数字的方法:

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

这是我尝试生成图像的HTML。

<html>
  <head>
    <title>{{ title }} - image</title>
  </head>
  <body>
    <img src={{ figure }} alt="Image Placeholder" height="100">
  </body>
</html>

而且,您可能会猜到,当我加载页面时,我得到的只是Image Placeholder。因此,他们不喜欢我提供的图形格式。

任何人都知道matplotlib的哪些方法/解决方法可以将图形转换为实际图像?我到处都是这些文档,但找不到任何东西。谢谢!

[顺便说一句:认为没有必要包含构成该图的python代码,但如果你们需要查看它,我可以将其包括在内(只是不想弄乱问题)

python html image matplotlib flask
5个回答
33
投票

您必须将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')

您的images.html模板将变为:

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

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')

我现在使用这样的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 %}

希望对某人有帮助。...


3
投票

我正在使用Python 3.x,我更改了一些代码行,并且对我有用。我收到以下错误消息:“ .....对象没有属性'savefig'”


1
投票
from flask import Flask, send_file
from io import StringIO
import matplotlib.pyplot as plt
from StringIO import StringIO
@app.route('/fig/')
def fig():
      plt.plot([1,2,3,4], [1,2,3,4])
      img = StringIO()
      plt.savefig(img)
      img.seek(0)
      return send_file(img, mimetype='image/png')

0
投票

Python 3

© www.soinside.com 2019 - 2024. All rights reserved.