Python:如何在烧瓶中显示matplotlib

时间:2018-06-06 19:41:55

标签: python matplotlib flask

我对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)

这是我的HTML:

<!doctype html>
<html>
   <body>

      <h1>Price Chart</h1>

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

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

   </body>
</html>

2 个答案:

答案 0 :(得分:23)

您可以在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

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

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

答案 1 :(得分:3)

正如@d parolin指出的那样,matplotlib生成的数字需要在被HTML呈现之前保存。要通过HTML在flask中投放图片,您需要将图片存储在flask文件目录中:

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

因此,在您的应用中,请使用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')

然后,在untitled1.html

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

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