如何在Plotly/Dash中默认选中单个图例项并取消其余项?
在Plotly/Dash中默认选中单个图例项的实现方案
要实现初始仅显示指定图例项、其余项处于未选中状态的效果,只需修改Plotly图表的trace可见性设置即可,具体步骤如下:
核心思路
Plotly的每个图表trace都支持visible属性,取值包括:
True:默认显示该trace'legendonly':默认隐藏该trace,且图例中对应项处于未选中状态(点击可切换显示)
我们只需遍历所有trace,将目标区域对应的trace设为True,其余设为'legendonly'即可。
修改后的完整代码
假设你希望默认显示West区域(可根据实际需求替换为你的目标区域名称),修改后的代码如下:
import plotly.express as px from dash import Dash, html, dcc # 假设df是你的数据源 # df = ... # 生成初始图表 fig = px.line(df, x='date', y='diesel_price', color='region', title='Diesel price in the US', labels={'date':'Date', 'diesel_price':'Price ($)', 'region':'Region'}) # 设置默认显示的目标区域 target_region = "West" # 遍历所有trace,设置可见性 for trace in fig.data: if trace.name == target_region: trace.visible = True else: trace.visible = 'legendonly' app.layout = html.Div([ html.H4('Metrics for trucking companies'), dcc.Graph(figure=fig), ]) if __name__ == '__main__': app.run_server(debug=True, host='0.0.0.0', port=8050)
关键说明
- 若不确定所有region的名称,可以通过
[trace.name for trace in fig.data]打印出所有trace的名称,再选择目标值。 'legendonly'状态的图例项不会显示对应曲线,但仍可通过点击图例切换为显示状态,完全保留交互性。
内容的提问来源于stack exchange,提问作者oToMaTiX
相关产品推荐
相关产品推荐

