如何基于Feature列用Plotly制作带下拉菜单的散点-柱状组合图?
实现带下拉菜单的Plotly散点-柱状组合图
步骤说明与代码实现
以下是完整的实现方案,基于pandas和plotly.graph_objects完成:
1. 导入依赖并加载数据
import pandas as pd import plotly.graph_objects as go # 加载数据集(替换为你的数据路径) df = pd.read_csv("PlotlyDropdown.csv")
2. 提取下拉菜单的选项
先获取Feature列的所有唯一值,作为下拉菜单的可选项:
feature_values = df["Feature"].unique()
3. 构建初始图表轨迹
默认显示第一个Feature对应的数据,其中:
- 用柱状图展示
depth_total - 用散点图分别展示
depth_5和depth_3
# 初始数据:第一个Feature对应的数据 initial_feature = feature_values[0] initial_data = df[df["Feature"] == initial_feature] # 创建轨迹 fig = go.Figure() # 柱状图:depth_total fig.add_trace(go.Bar( x=initial_data["chrPos"], y=initial_data["depth_total"], name="depth_total", marker_color="#1f77b4" )) # 散点图:depth_5 fig.add_trace(go.Scatter( x=initial_data["chrPos"], y=initial_data["depth_5"], name="depth_5", mode="markers", marker_color="#ff7f0e", marker_size=8 )) # 散点图:depth_3 fig.add_trace(go.Scatter( x=initial_data["chrPos"], y=initial_data["depth_3"], name="depth_3", mode="markers", marker_color="#2ca02c", marker_size=8 ))
4. 配置下拉菜单
为每个Feature值创建一个按钮,点击时更新所有轨迹的数据源:
# 构建下拉按钮列表 buttons = [] for feat in feature_values: # 获取当前Feature对应的数据 filtered_data = df[df["Feature"] == feat] # 定义每个按钮的更新参数:更新三个轨迹的x和y数据 button = dict( label=feat, method="update", args=[ { "x": [filtered_data["chrPos"], filtered_data["chrPos"], filtered_data["chrPos"]], "y": [filtered_data["depth_total"], filtered_data["depth_5"], filtered_data["depth_3"]] }, { "title": f"Feature: {feat}" # 更新图表标题 } ] ) buttons.append(button) # 将下拉菜单添加到图表布局 fig.update_layout( updatemenus=[ dict( buttons=buttons, direction="down", showactive=True, x=0.1, xanchor="left", y=1.15, yanchor="top" ) ], title=f"Feature: {initial_feature}", xaxis_title="chrPos", yaxis_title="Depth Values", legend_title="Depth Type" ) # 显示图表 fig.show()
关键说明
- 下拉菜单通过
updatemenus配置,每个按钮使用update方法同步更新所有轨迹的数据源 - 柱状图和散点图的样式可根据需求调整(如颜色、标记大小等)
- 图表标题会随下拉选项切换自动更新,提升可读性
内容的提问来源于stack exchange,提问作者YouCook21
相关产品推荐
相关产品推荐

