Python绘图API:如何通过flaskapi公开科学的Python绘图?

2024-05-19 06:45:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从烧瓶表格的数据中创建一个绘图。 我已经在尝试thatthat在下一个网页中显示matplotlib分散,以及如何看到我不知道怎么做,因为没有人能解释给我看

那么,你能告诉我如何在网页上散布python数据吗。 最好是在单一的网页与形式。在

我还检查了matplotlib运行得很慢,kek

添加

但在填写完下一页的图片后,我该怎么显示呢?在

我想我需要另一个烧瓶.func像这样:


from flask import Flask, render_template, url_for, redirect, send_file, make_response
from forms import AAForm
from create_plot import ploter
import os

app = Flask(__name__)

SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY

@app.route('/', methods=['GET', 'POST']) 
def index():
    form = AAForm()
    if form.validate_on_submit():
        return render_template('img.html', url='/kek')
    return render_template('index.html', form=form)

@app.route('/kek', methods=['GET', 'POST']) 
def img(form):
    bytes_obj = ploter(form.uniprot_id.data, ['K', 'R', 'H'])

    return send_file(bytes_obj,
                     attachment_filename='plot.png',
                     mimetype='image/png')

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

还有这个:

^{pr2}$

但我不明白我该怎么送表格数据致图像功能在


Tags: 数据keyfromimportformapp网页secret
1条回答
网友
1楼 · 发布于 2024-05-19 06:45:47

绘制数据

这里的一个可能的方法是构建一个返回数据的API,并让应用程序的前端使用一个或多或少复杂的javascript图表库来呈现数据。在

我们需要哪些组件:

数据集:scikit learn的乳腺癌数据集示例。在

一个图:首先从seaborn得到一个简单的相关图。在

一个API:使用烧瓶创建简单的API。在

首先加载数据并绘制图

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import io
from sklearn.datasets import load_breast_cancer
def do_plot():
    # Loading 
    data = load_breast_cancer()
    breast_cancer_df = pd.DataFrame(data['data'])
    breast_cancer_df.columns = data['feature_names']
    breast_cancer_df['target'] = data['target']
    breast_cancer_df['diagnosis'] = [data['target_names'][x] for x in data['target']]
    feature_names= data['feature_names']

    corr = breast_cancer_df[list(feature_names)].corr(method='pearson')

    f, ax = plt.subplots(figsize=(11, 9))
    cmap = sns.diverging_palette(220, 10, as_cmap=True)
    mask = np.zeros_like(corr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
                square=True, linewidths=.5, cbar_kws={"shrink": .5})

    # here is the trick save your figure into a bytes object and you can #afterwards expose it via flas
    bytes_image = io.BytesIO()
    plt.savefig(bytes_image, format='png')
    bytes_image.seek(0)
    return bytes_image

这将导致下图:

Image representing the plot

现在通过flask API公开这个BytesIO对象。在

^{pr2}$

如果您的服务器在本地主机上运行,映像将在http://localhost:5000/plots/breast_cancer_data/correlation_matrix下可用。在

为了让最终用户访问绘图,将数据集成到HTML网站中。你只需在html正文中包含数据,它就可以开箱即用了。在

参考:You can get more info here

相关问题 更多 >

    热门问题