1.Plotly Express
模块:
首先查看Plotly Express文档,可以看到官方给出了一系列使用各类数据集生成的图表实例:
2.Plotly Express
模块和Dash共用:
本次使用NBA 2019-2020赛季的球员数据为数据源,构建数据图表。main.py
文件代码:
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
df = pd.read_csv("data/NBA.csv")
fig = px.scatter(df, x="player_height", y="pts")
# 构建一个Graph对象
graph = dcc.Graph(figure=fig)
# 构建dash应用
app = dash.Dash(__name__)
# 设定页面布局样式
app.layout =html.Div(children=[graph])
app.run_server(debug=True)
运行代码,浏览器打开http://127.0.0.1:8050/
,最终效果图如下所示:
3.构建动态交互图表:
本次使用dcc中的Default Dropdown
组件,通过官方文档查看相关内容。
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
df = pd.read_csv("data/NBA.csv")
# 构建一个Graph对象
graph = dcc.Graph(figure=px.scatter(x=df["player_height"], y=df["pts"]),id="fig")
# 构建一个Dropdown对象
drop_down = dcc.Dropdown(
id='dropdown',
options=[
{'label': 'player_height', 'value': 'player_height'},
{'label': 'player_weight', 'value': 'player_weight'},
{'label': 'player_age', 'value': 'age'}
],
value='player_height'
)
# 构建dash应用
app = dash.Dash(__name__)
# 构建数据流向
@app.callback(Output("fig","figure") , [Input("dropdown","value")])
def update(v):
return px.scatter(x=df[v], y=df["pts"])
# 设定页面布局样式
app.layout =html.Div(children=[drop_down , graph])
app.run_server(debug=True)
运行代码,浏览器打开http://127.0.0.1:8050/
,最终效果图如下所示:
点击浏览器中的调试图标中的Callback
按钮,可以查看当前的数据流向: