【Dash】图表交互:单选按钮 dcc.RadioItems()

一、Controls and Callbacks

So far you have build a static app that displays tabular data and a graph. However, as you develop more sophisticated Dash apps, you will likely want to give the app user more freedom to interact with the app and explore the data in greater depth. To achieve that, you will need to add controls to the app by using the cllback function.

In this example we will add radio buttons to the app layout. Then, we will build the callback to create the interaction between the radio buttons and the histogram chart.

# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = html.Div([
    html.H1('My Dashboard', style={'color': 'blue', 'fontSize': '20px', 'textAlign': 'center'}),
    html.Div(children='My First App with Data, Graph, and Controls', style={'color': 'blue', 'fontSize': '20px', 'textAlign': 'center'}),
    dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', id='controls-and-radio-item'),
    html.Hr(),
    dash_table.DataTable(data=df.to_dict('records'), page_size=6),
    html.Hr(),
    dcc.Graph(figure={}, id='controls-and-graph')
])

# Add controls to build the interaction
@callback(
    Output(component_id='controls-and-graph', component_property='figure'),
    Input(component_id='controls-and-radio-item', component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)

二、解读

创建一个带有数据、图表和控件的交互式仪表板。

# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
  • 导入所需的Python包,用于构建Web应用(Dash),数据处理(pandas)和数据可视化(plotly.express)。
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

用 pandas 的 read_csv 函数从 URL 中将 CSV 数据文件加载到 DataFram df 中。

app = Dash()
app.layout = html.Div([
   # ...... coding .....
)]
  •  创建一个Dash应用实例
  • 设置应用的布局,使用 html.Div 作为根容器。
html.H1('My Dashboard', style={'color': 'blue', 'fontSize': '20px', 'textAlign': 'center'})
  • 添加一个标题(html.H1)到布局并设置样式,颜色为蓝色、字体20px,居中。
html.Div(children='My First App with Data, Graph, and Controls', style={'color': 'blue', 'fontSize': '20px', 'textAlign': 'center'})
  • 添加一个容器(html.Div),并设置文本(children)和样式(style)。
dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', id='controls-and-radio-item')
  • 添加单选按钮控件(dcc.RadioItems),设置选项(options)为 pop、lifeExp、gdpPercap,初始值(value)为 lifeExp,控件的 id 为 controls-and-radio-item。
html.Hr()
  • 添加一个水平分割线。
dash_table.DataTable(data=df.to_dic('records'), page_size=6)
  • 添加表格组件(dash_table.DataTable),显示数据框 df 的数据,每行显示6条记录。
  • df.to_dic('record') 将 DataFrame df 的数据转换为字典列表,其中每个字典代表 DataFrame 的一行。这种方法返回的字典列表的每个元素都是一个字典,其键是列名,值是对应的行数据。
dcc.Graph(figure={}, id='controls-and-graph')
  • 添加图表组件(dcc.Graph),初始图表数据为空(figure={}),图表的 ID 是 controls-and-graph。

figure={}是什么意思?

  • 当没有数据来生成图表时,figure={} 空字典充当了初始值,确保组件可以被正确渲染到页面上
  • 通过回调函数,figure 属性将在后续根据用户交互动态更新。空字典作为起点,当回调函数被触发时,它会被新的图表数据和配置所替换。
  • 如果不为 figure 属性提供值,或者使用 None,可能会导致组件在初始化时无法正确渲染或显示。
  • 总结来说,figure={} 在 dcc.Graph 组件的初始化中是一个占位符,用于确保组件可以被渲染,而实际的图表数据和配置将在应用运行过程中通过回调函数动态设置。
@callback(
    Output(component_id='controls-and-graph', component_property='figure'),
    Input(component_id='controls-and-radio-item', component_property='value')
)

def update_graph(col_chosen):
    # ..... coding ......
 
  •  定义一个回调函数,根据 dcc.RadioItems 控件用户选中的值(component_property='value'),动态更新 dcc.Graph 组件的图表,component_property='figure' 表示 dcc.Graph 组件的 figure 属性,该属性用于设置图表的数据和配置。
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig
  • 在回调函数内,使用 plotly.express 的 px.histogram 创建一个直方图, X 轴是 'continent' ,Y 轴是选中的列(col_chosen),并计算直方图的均值。 
  • 返回图表对象 fig ,Dash 将使用这个对象更新图表组件。

 

  • 35
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值