0
点赞
收藏
分享

微信扫一扫

【Python数据可视化】Flask结合Plotly在网页上展示图表

橙子好吃吗 2022-02-10 阅读 99

Flask 文件

import json

import pandas as pd
import plotly
import plotly.express as px
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def notdash():
    df = pd.DataFrame({
        'Fruit': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Oranges',
                  'Bananas'],
        'Amount': [4, 1, 2, 2, 4, 5],
        'City': ['SF', 'SF', 'SF', 'Montreal', 'Montreal', 'Montreal']
    })
    fig = px.bar(df, x='Fruit', y='Amount', color='City',
                 barmode='group')

    fig2 = px.bar(df, x='Fruit', y='Amount')
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    graphJSON2 = json.dumps(fig2, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('plotly_charts.html', graphJSON=graphJSON, graphJSON2=graphJSON2)


app.run(debug=True)

模板文件

文件名:templates/plotly_charts.html

<!doctype html>
<html>
 <body>
  <h1>Hello Plotly (but not Dash)</h1>
  <div id='chart' class='chart'></div>
  <div id='chart2' class='chart'></div>
</body>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
  var graphs = {{graphJSON | safe}};
  Plotly.plot('chart',graphs,{});

  var graphs2 = {{graphJSON2 | safe}};
  Plotly.plot('chart2',graphs2,{});
</script>
</html>

效果展示

在这里插入图片描述

参考地址:

https://towardsdatascience.com/web-visualization-with-plotly-and-flask-3660abf9c946

举报

相关推荐

0 条评论