Python:如何在烧瓶中显示matplotlib

Python: How to show matplotlib in flask

本问题已经有最佳答案,请猛点这里访问。

我对烧瓶和Matplotlib很陌生。我想展示一个我用HTML生成的简单图表,但是我很难弄清楚它是如何生成的。下面是我的python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!doctype html>
<html>
   <body>

      Price Chart

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

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

   </body>
</html>


您可以在fly-in-flask URL路由处理程序中生成图像:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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模板中包含图像:

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

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

1
2
3
4
static/
  images/
    plot.png --> store plots here
templates/

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

1
2
3
4
5
6
@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中:

1
2
3
4
5
  <p>
{{ name }}
</p>

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