【问题标题】:from flask, how to send the matplotlib plot image to html?从烧瓶中,如何将 matplotlib 绘图图像发送到 html?
【发布时间】:2018-08-24 04:17:53
【问题描述】:

在flask中,如何让matplotlib中plt保存的图像显示在网页上?下面的 python 代码创建了一个绘图并将其保存为.png 图像。 HTML 文件也随之而来。当我运行它时,我得到了错误提示:

TypeError: expected str, bytes or os.PathLike object, not NoneType.

任何可以帮助我的人请告诉我该怎么做。

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

@app.route('/fig/<air_quality>')
def fig(air_quality):
    import matplotlib.pyplot as plt
    import numpy as np
    from io import BytesIO

    img = BytesIO()
    pm10 = np.array(['23', '45', '56', '12'])
    pm25 = np.array(['34', '56', '59', '34'])
    dates = np.array(['2017-12-20', '2017-12-21', '2017-12-22', '2017-12-23'])

    plt.figure(figsize=(12, 8), dpi=100, facecolor='1.0')
    plt.title("GangNam", fontsize=20)
    plt.plot_date(dates, pm10, 'rs--', label='pm10')
    plt.plot_date(dates, pm25, 'gs--', label='pm25')
    plt.legend()
    img = plt.savefig('img.png')
    return send_file(img, mimetype='image/png')

我不在这里如何显示 HTML 文件。但是该文件在img 标签内有这个:

src="{{url_for('fig', air_quality = title)}}

【问题讨论】:

    标签: python html matplotlib flask


    【解决方案1】:

    您可以将 pylab 图形保存到内存文件中,例如 BytesIO(py3)、StringIO(py2)。

    plt.savefig(img, format='png')
    img.seek(0)
    
    response=make_response(img.getvalue())
    response.headers['Content-Type'] = 'image/png'
    img.close()
    return response
    

    【讨论】:

    • @BdginMan 请您帮忙。修复我的代码,以便我弄清楚如何运行它?
    • 我做了,但是错误像 TypeError 一样爆发:描述符 'write' 需要一个 '_io.BytesIO' 对象但收到了一个 'bytes'
    猜你喜欢
    • 2019-04-22
    • 2017-10-20
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    相关资源
    最近更新 更多