使用 Python Flask 在 HTML 上返回 plt.show()

Returning plt.show() on HTML with Python Flask

我正在使用 Python Flask 从一个简单的 html 文件中获取输入。 HTML 要求用户输入一个状态,当他们输入状态时,我希望输出是一个图。

我有以下创建 Python Flask 的代码,但是当用户输入状态时,绘图输出在我的 Jupyter Notebook 文件中而不是 HTML 页面上。

我见过使用 Figure() 使绘图显示在 HTML 页面上的方法,但我不确定如何使用 figure 函数重新创建当前绘图。

app = Flask(__name__)

@app.route('/')
def form():
    return render_template("flask_form.html")

@app.route('/', methods = ['POST'])
def form_post():
    state = request.form['userinput']
    
    dff = df[df['state'] == state]
    dff['total_icu_beds_7_day_avg'] = dff['total_icu_beds_7_day_avg'].astype(float)
    dff['total_beds_7_day_avg'] = dff['total_beds_7_day_avg'].astype(float)
    dff['inpatient_beds_7_day_avg'] = dff['inpatient_beds_7_day_avg'].astype(float)
    
    pivot = np.round(dff.pivot_table(index = ["collection_week"], values = ["total_icu_beds_7_day_avg", "total_beds_7_day_avg", "inpatient_beds_7_day_avg"], aggfunc = [np.mean]), 0)
    pivot.columns = ['Inpatient 7 day Avg', 'Total Beds 7 day Avg', 'Total ICU Beds 7 day Avg']
    pivot = pivot.reset_index()
    
    x = pivot['collection_week']
    y1 = pivot['Inpatient 7 day Avg']
    y2 = pivot['Total Beds 7 day Avg']
    y3 = pivot['Total ICU Beds 7 day Avg']
    
    title = str(state + " State Staffed Beds")

    plt.figure(figsize=(16,6))
    plt.plot(x, y1, label = 'Inpatient AVG', color = 'blue')
    plt.plot(x, y2, label = 'Total Beds AVG', color = 'red')
    plt.plot(x, y3, label = 'Total ICU Beds AVG', color = 'cyan')
    plt.legend()
    plt.title(title, fontweight = 'bold')
    plt.ylabel("Number of Staffed Beds")
    plt.xlabel("Date")
    plt.show()

这是我的 HTML 代码,我知道情节需要在输出中但不确定如何编码:

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Hospital Capacity by State</h1>
    <p>Enter the abbreviation of your desired state:</p>
    <form action="." method="POST">
        <input type="text" name="userinput">
        <input type="submit" name="my-form" value="Send">
        <output> </output>
    </form>
</body>
</html>

Python Flask 代码:

app = Flask(__name__)

@app.route('/')
def form():
    return render_template("flask_form_plot.html")

@app.route('/', methods = ['POST'])
def form_post():
    state = request.form['userinput']
    
    dff = df[df['state'] == state]
    dff['total_icu_beds_7_day_avg'] = dff['total_icu_beds_7_day_avg'].astype(float)
    dff['total_beds_7_day_avg'] = dff['total_beds_7_day_avg'].astype(float)
    dff['inpatient_beds_7_day_avg'] = dff['inpatient_beds_7_day_avg'].astype(float)
    
    pivot = np.round(dff.pivot_table(index = ["collection_week"], values = ["total_icu_beds_7_day_avg", "total_beds_7_day_avg", "inpatient_beds_7_day_avg"], aggfunc = [np.mean]), 0)
    pivot.columns = ['Inpatient 7 day Avg', 'Total Beds 7 day Avg', 'Total ICU Beds 7 day Avg']
    pivot = pivot.reset_index()

    x = pivot['collection_week']
    y1 = pivot['Inpatient 7 day Avg']
    y2 = pivot['Total Beds 7 day Avg']
    y3 = pivot['Total ICU Beds 7 day Avg']
    
    plt.figure(figsize=(16,6))
    plt.plot(x, y1, label = 'Inpatient AVG', color = 'blue')
    plt.plot(x, y2, label = 'Total Beds AVG', color = 'red')
    plt.plot(x, y3, label = 'Total ICU Beds AVG', color = 'cyan')
    plt.legend()
    plt.title(str(state) + " State Staffed Beds", fontweight = 'bold')
    plt.ylabel("Number of Staffed Beds")
    plt.xlabel("Date")

    img = io.BytesIO()
    plt.savefig(img, format = 'png')
    img.seek(0)
    plot_data = urllib.parse.quote(base64.b64encode(img.read()).decode())
    return render_template('flask_form_plot.html', plot_url = plot_data)

HTML代码:

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Hospital Capacity by State</h1>
    <p>Enter the abbreviation of your desired state:</p>
    <form action="." method="POST">
        <input type="text" name="userinput">
        <input type="submit" name="my-form" value="Send">
        <br>
        <br>
        <output> <img src="data:image/png;base64, {{ plot_url }}" width="1000" height="500" alt="graph"> </output>
    </form>
</body>
</html>