Python:如何在烧瓶中显示matplotlib [英] Python: How to show matplotlib in flask

查看:78
本文介绍了Python:如何在烧瓶中显示matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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>

推荐答案

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

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

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模板中添加图片:

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

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

这篇关于Python:如何在烧瓶中显示matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆