Python:如何在烧瓶中显示 matplotlib

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50728328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:35:10  来源:igfitidea点击:

Python: How to show matplotlib in flask

pythonmatplotlibflask

提问by SVill

I'm very new to Flask and Matplotlib. I'd like to be able to show a simple chart I generated in some html, but I'm having a very hard time figuring out how. Here is my Python code:

我对 Flask 和 Matplotlib 很陌生。我希望能够显示我在一些 html 中生成的简单图表,但我很难弄清楚如何。这是我的 Python 代码:

from flask import Flask, render_template
import numpy as np
import pandas
import matplotlib.pyplot as plt

app = Flask(__name__)
variables = pandas.read_csv('C:\path\to\variable.csv')
price =variables['price']


@app.route('/test')
def chartTest():
    lnprice=np.log(price)
    plt.plot(lnprice)
    return render_template('untitled1.html', name = plt.show())

if __name__ == '__main__':
   app.run(debug = True)

And here is my HTML:

这是我的 HTML:

<!doctype html>
<html>
   <body>

      <h1>Price Chart</h1>

      <p>{{ name }}</p>

      <img src={{ name }} alt="Chart" height="42" width="42">

   </body>
</html>

回答by Messa

You can generate the image on-the-fly in Flask URL route handler:

您可以在 Flask URL 路由处理程序中即时生成图像:

import io
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

@app.route('/plot.png')
def plot_png():
    fig = create_figure()
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')

def create_figure():
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    xs = range(100)
    ys = [random.randint(1, 50) for x in xs]
    axis.plot(xs, ys)
    return fig

Then you need to include the image in your HTML template:

然后你需要在你的 HTML 模板中包含图像:

<img src="/plot.png" alt="my plot">

回答by Ajax1234

As @d parolin pointed out, the figure generated by matplotlibwill need to be saved before being rendered by the HTML. In order to serve images in flaskby HTML, you will to store the image in your flaskfile directory:

正如@d parolin 指出的那样,生成的图形matplotlib在被 HTML 渲染之前需要保存。为了flask通过 HTML提供图像,您需要将图像存储在您的flask文件目录中:

static/
  images/
    plot.png --> store plots here
templates/

Therefore, in your application, use plt.savefig:

因此,在您的应用程序中,使用plt.savefig

@app.route('/test')
def chartTest():
  lnprice=np.log(price)
  plt.plot(lnprice)   
  plt.savefig('/static/images/new_plot.png')
  return render_template('untitled1.html', name = 'new_plot', url ='/static/images/new_plot.png')

Then, in untitled1.html:

然后,在untitled1.html

  <p>{{ name }}</p>

  <img src={{ url}} alt="Chart" height="42" width="42">