如何在Dash应用中添加支持变量选择的数据集直方图?
Dash直方图添加解决方案
修复后的完整代码
import dash import pandas as pd import plotly.express as px from dash import Input, Output, dash_table, dcc, html app = dash.Dash(__name__) df = pd.read_csv('C:\\Users\\Programming\\diamonds.csv') app.layout = html.Div([ html.H1("Diamonds", style={'text-align': 'center'}), html.Div(["Choose the number of observations x*: ", dcc.Input(id='top_of_table', value=10, type='number')]), dash_table.DataTable(id="any_id"), html.H1("Description", style={'text-align': 'center'}), html.Div("""This is a dataframe containing 11 variables on Diamonds. The variables are the following: price, carat, clarity, cut, color, depth, table, x, y, z, and date. Range in price is $338-$18791. Carats or weight of the diamond ranges from .2-3.0."""), # 变量选择下拉框 html.Div([ "Select variable for histogram: ", dcc.Dropdown( id='hist_var', options=[{'label': col, 'value': col} for col in df.columns], value=df.columns[0], # 默认选中第一列变量 style={'width': '50%'} ) ], style={'margin-top': '20px'}), # 直方图显示区域(位于描述文本下方) dcc.Graph(id='histogram', style={'margin-top': '20px'}) ]) @app.callback( Output(component_id="any_id", component_property='data'), Input(component_id='top_of_table', component_property='value'), ) def update_table(num_observ): # 修复表格逻辑:根据用户输入的数量返回数据 df1 = df.head(num_observ) return df1.to_dict('records') @app.callback( Output(component_id='histogram', component_property='figure'), Input(component_id='hist_var', component_property='value'), ) def update_histogram(selected_var): # 生成选中变量的交互式直方图 fig = px.histogram(df, x=selected_var, title=f'Histogram of {selected_var}') fig.update_layout(xaxis_title=selected_var, yaxis_title='Count') return fig if __name__ == '__main__': app.run_server(debug=True)
关键改动说明
- 导入绘图工具:新增
plotly.express as px,用官方推荐的快速绘图库生成交互式直方图 - 添加变量选择控件:通过
dcc.Dropdown生成所有11个变量的选项,默认选中第一列,用户可自由切换 - 放置直方图容器:将
dcc.Graph组件放在描述文本和下拉框下方,完全匹配你的位置需求 - 修复表格回调:原代码固定返回前10行数据,改为根据用户输入的
num_observ动态返回,让输入控件真正生效 - 直方图回调逻辑:用户切换变量时自动触发回调,生成对应变量的直方图,并设置清晰的标题和坐标轴标签
内容的提问来源于stack exchange,提问作者camaya3
相关产品推荐
相关产品推荐

