user11665931
user11665931

Reputation:

Python Plotting API: How to expose your scientific python plots through a flask API?

I need to create a plot from data from flask form. I was already trying that and that to show matplotlib scatter in the next webpage and how you can see I don't know how to do it, because no one couldn't explain me that

So, can u advice to me how to do scatter with python data in the webpage. It would be better if it be in the single webpage with form.

Also I checked that matplotlib works so slowly, kek

Added

But how can I show image in the in the next page after filling form?

I suppose that I need use another flask.func like that:


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)

and this:

<img src="{{ url }}">

But I don't understand how can I send form.data to the img.func

Upvotes: 1

Views: 2147

Answers (1)

Abdullah Akhtar
Abdullah Akhtar

Reputation: 558

Plot the data

A possible approach here would be to build an API that returns data and let the front-end of the application render the data with a more or less complex javascript charting library.

What components do we need:

A dataset: An example of the breast cancer dataset from scikit-learn.

A plot: Take a simple correlation plot from seaborn for starters.

An API: Create simple API with the use of flask.

First load the data and do a plot

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

This will result in the plot below:

Image representing the plot

Now expose this BytesIO object through a flask API.

from flask import Flask, send_file, make_response, 
from plot import do_plot
app = Flask(__name__)

@app.route('/plots/breast_cancer_data/correlation_matrix', methods=['GET'])
def correlation_matrix():
    bytes_obj = do_plot()

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

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

if your server runs on localhost the image will be available under http://localhost:5000/plots/breast_cancer_data/correlation_matrix.

In order to let end users access the plot, integrate the data in an HTML website. You can just include the data in html body and it will work out of the box.

REFERENCE: You can get more info here

Upvotes: 2

Related Questions