阅读 90

Matplotlib-网页展示

  1. 直接展示

import io
from flask import Response
import matplotlib as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from flask import Flask
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
app = Flask(__name__)

@app.route(‘/print-plot‘)
def plot_png():
   fig = Figure()
   axis = fig.add_subplot(1, 1, 1)
   xs = np.random.rand(100)
   ys = np.random.rand(100)
   axis.plot(xs, ys)
   output = io.BytesIO()  # 数据读写不一定是文件,也可以在内存中读写
   FigureCanvas(fig).print_png(output)
   return Response(output.getvalue(), mimetype=‘image/png‘)

app.run(debug = True)
  1. 直接展示【保存图片到内存】
# python -m pip install -U scikit-image
import io
from flask import Flask, send_file
import numpy as np
from skimage.io import imsave
import matplotlib.pyplot as plt

app = Flask(__name__)
app.debug = True


@app.route(‘/‘)
def generate_image():
    """
    Return a generated image as a png by
    saving it into a StringIO and using send_file.
    """
    num_tiles = 20
    tile_size = 30
    arr = np.random.randint(0, 255, (num_tiles, num_tiles, 3))
    arr = arr.repeat(tile_size, axis=0).repeat(tile_size, axis=1)

    # We make sure to use the PIL plugin here because not all skimage.io plugins
    # support writing to a file object.
    strIO = io.BytesIO()
    imsave(strIO, arr, plugin=‘pil‘, format_str=‘png‘)
    strIO.seek(0)
    return send_file(strIO, mimetype=‘image/png‘)


@app.route(‘/plot‘)
def generate_plot():
    """
    Return a matplotlib plot as a png by
    saving it into a StringIO and using send_file.
    """
    def using_matplotlib():
        fig = plt.figure(figsize=(6, 6), dpi=300)
        ax = fig.add_subplot(111)
        x = np.random.randn(500)
        y = np.random.randn(500)
        ax.plot(x, y, ‘.‘, color=‘r‘, markersize=10, alpha=0.2)
        ax.set_title(‘Behold‘)
        strIO = io.BytesIO()
        plt.savefig(strIO, dpi=fig.dpi)
        strIO.seek(0)
        return strIO

    strIO = using_matplotlib()
    return send_file(strIO, mimetype=‘image/png‘)


if __name__ == ‘__main__‘:
    app.run()
  1. 保存图片显示(文件)
# https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask

In order to serve images in flask by HTML, you will need to store the image in your flask file directory:

static/
  images/
    plot.png --> store plots here
templates/
Therefore, in your application, use plt.savefig:

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

@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:

  

{{ name }}

Chart

Price Chart

{{ name }}

Chart

原文:https://www.cnblogs.com/amize/p/15060978.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐