如何在按下按钮时删除图形?

问题描述 投票:0回答:1

到目前为止,我有一个flask应用程序,在该应用程序中,我为给定的数据帧计算线性回归。然后,我使用JSON将图转储到HTML。单击时有一个按钮,显示线性回归图。我想在下拉列表中选择预测算法:Facebook先知,线性回归和多项式回归。但是,一旦我从列表中选择了另一种算法,如何删除图形呢?

非常感谢您的帮助!

app.py的代码是:

from flask import Flask, render_template  # this has changed
import plotly
import plotly.graph_objs as go

import pandas as pd
import numpy as np
import json

# for another file...
import datetime as dt
import numpy as np
import pandas as pd
from distributed.deploy.ssh import bcolors
from pandas.plotting import register_matplotlib_converters
from plotly import graph_objs as go
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split

register_matplotlib_converters()


def calculate_linear_regression(data, sensor_name):
    data = pd.read_csv(data)  #
    data['day'] = pd.to_datetime(data['day'], format="%d/%m/%Y")  #

    data = data.sort_values(by=['readable time'])
    group_by_df = pd.DataFrame([name, group.mean()[sensor_name]] for name, group in data.groupby('day'))
    group_by_df.columns = ['day', sensor_name]
    group_by_df['day'] = pd.to_datetime(group_by_df['day'])
    group_by_df['day'] = group_by_df['day'].map(dt.datetime.toordinal)

    def split(group_by_df):
        X = group_by_df[['day']].values
        y = group_by_df[[sensor_name]].values
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=False)
        return X_train, X_test, y_train, y_test

    X_train, X_test, y_train, y_test = split(group_by_df)

    def analyse_forecast():
        print(bcolors.OKBLUE + "MSE linear regression(mean squared error)",
              mean_squared_error(group_by_df[sensor_name], group_by_df['predicted']), bcolors.ENDC)
        print("r2 score ", r2_score(group_by_df[sensor_name], group_by_df['predicted']))
        rmse = np.sqrt(mean_squared_error(group_by_df[sensor_name], group_by_df['predicted']))
        print(bcolors.WARNING + "RMSE for linear regression=", rmse, bcolors.ENDC)
        print(bcolors.OKBLUE + "MSE TEST ", mean_squared_error(y_test, group_by_df['predicted'][len(X_train):]),
              bcolors.ENDC)
        print("r2 score TEST", r2_score(y_test, group_by_df['predicted'][len(X_train):]))
        return mean_squared_error(group_by_df[sensor_name], group_by_df['predicted'])

    def calculate_linear_reg():
        group_by_df.reset_index(inplace=True)
        mse_list = []

        model = LinearRegression()
        model.fit(X_train, y_train)
        y_pred = model.predict(group_by_df[['day']])
        group_by_df['predicted'] = y_pred
        mse_list.append(analyse_forecast())

    calculate_linear_reg()
    return group_by_df, X_train, sensor_name


group_by_df, X_train, sensor_name = calculate_linear_regression(
    "https://raw.githubusercontent.com/iulianastroia/csv_data/master/final_dataframe.csv",
    "ch2o")


def create_figure(group_by_df, X_train, sensor_name):
    linear_regression_fig = go.Figure()

    # plot predicted values
    linear_regression_fig.add_trace(go.Scatter(
        x=group_by_df['day'].map(dt.datetime.fromordinal),
        y=group_by_df['predicted'],
        name="linear regression",
        mode='lines+markers',
        marker=dict(
            color=np.where(group_by_df['day'].index < len(X_train), 'red', 'green'))))

    # plot actual values
    linear_regression_fig.add_trace(go.Scatter(
        x=group_by_df['day'].map(dt.datetime.fromordinal),
        y=group_by_df[sensor_name],
        name='ACTUAL values',
        mode='lines+markers'))

    linear_regression_fig.update_layout(
        title='Linear regression for ' + sensor_name,
        yaxis_title=sensor_name,
        xaxis_title='Day',
        showlegend=True)
   # linear_regression_fig.show()
    graphJSON = json.dumps(linear_regression_fig, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON

def create_plot():
    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
        y=[0, 1, 2, 3, 4, 5, 6, 7, 8],
        mode="lines+markers",
        name="Name of Trace 1"  # this sets its legend entry
    ))

    fig.add_trace(go.Scatter(
        x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
        y=[1, 0, 3, 2, 5, 4, 7, 6, 8],
        name="Name of Trace 2"
    ))

    fig.update_layout(
        title="Plot Title",
        xaxis_title="x Axis Title",
        yaxis_title="y Axis Title",
        font=dict(
            family="bahnschrift",
            size=18,
            color="#7f7f7f"
        )
    )
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON


app = Flask(__name__)


@app.route('/')
def index():
    bar = create_figure(group_by_df, X_train, sensor_name)
    return render_template('index.html', scatter_plot=bar)

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

而index.html是:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>My First Dashboard</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
</head>
<body>
                        <input type="submit" id="send_message" name="send_message" class="btn btn-outline-secondary"
                               value="Linear Regression" onclick="show_plot()" />

<div class="chart" id="bargraph">
    <script>
    function show_plot(){
        var graphs = {{scatter_plot | safe}};
        Plotly.plot('bargraph',graphs,{});}
    </script>
</div>
</body>
</html>
python html flask regression plotly
1个回答
0
投票

如果我理解正确,您有多组数据,并且希望能够选择每组数据以显示在网页上的表格中。我不会尝试在同一“页面”上加载不同的数据集。这是我为我的一个项目所做的一个示例。

我的索引页面具有以下形式,可用于从数据库中加载选项。 drpdwn对象包含我的选项列表。

menu_tol.py

...
@bp.route('/menu_tol')
def index(tol_id=0):
    db=get_db()
    menu_query='SELECT * FROM tol'
    drpdwn=db.execute(menu_query).fetchall()
    close_db()
    return render_template(
      'menu_tol/index.html',
      drpdwn=drpdwn
    )

menu_tol / index.html

<form name"tol_form" action="/menu_tol/update" method='POST'>
  <select name="tol_select">
  {% for tol in drpdwn %}
    <option value={{tol.id}}>{{tol.name}}</option>
  {% endfor %}
  </select>
  <input type="submit" value="Submit">
</form>

用户从此处选择一个对象,然后单击一个按钮。该脚本使用该值来生成特定于我选择的新URL。然后,第二页将包含该请求所独有的所有信息。这样,html页面仅显示其给出的内容,而我不必考虑多个可能性。

@bp.route('/menu_tol/update', methods=('GET','POST'))
def update():

    if request.method=='POST':
        tol_id=request.form['tol_select']
        return redirect(url_for('.summary', tol_id=tol_id))

@bp.route('/menu_tol/<tol_id>/summary', methods=('GET','POST'))
def summary(tol_id):
    db=get_db()
    tol_query='SELECT name FROM tol WHERE id = ' + tol_id
...
    return render_template(
      'menu_tol/summary.html',
      tol_title=tol_title,
      result_list=result_list,
      tol_id=tol_id
    )

最后,如果要“清除”结果,只需创建一个对象,即可将您重定向到index页面。

<a style="color:blue" class="action" href="/menu_tol"><b>TOL</b></a> - TOL Archive
© www.soinside.com 2019 - 2024. All rights reserved.