如何创建Plotly按钮实现散点图(ScatterPlot)数据点的显示隐藏控制
Plotly 散点图交互筛选按钮实现方案
核心args参数写法
你需要通过修改散点 trace 的选中状态配置,将未选中点的透明度设为0实现隐藏效果,布尔数组可直接赋值给selectedpoints字段,对应位置为True即展示该索引的数据点:
# button_1 示例:仅展示索引1、2、3对应数据点 args=[ { # 布尔数组长度需和总数据点数量完全一致 "selectedpoints": [False, True, True, True, False, False, False, False, False, False], "selected": {"marker": {"opacity": 1}}, "unselected": {"marker": {"opacity": 0}} } ]
完整可运行示例
import plotly.express as px import pandas as pd import numpy as np # 生成10个测试散点 points = np.random.rand(10, 2) df = pd.DataFrame(points, columns=["x", "y"]) fig = px.scatter(df, x="x", y="y") fig.update_layout( updatemenus=[ dict( type="buttons", x=0.1, y=1.2, buttons=[ # 仅展示索引1、2、3的点 dict( method="restyle", label="button_1", args=[ { "selectedpoints": [False, True, True, True, False, False, False, False, False, False], "selected": {"marker": {"opacity": 1}}, "unselected": {"marker": {"opacity": 0}} } ] ), # 仅展示索引4、5、6的点 dict( method="restyle", label="button_2", args=[ { "selectedpoints": [False, False, False, False, True, True, True, False, False, False], "selected": {"marker": {"opacity": 1}}, "unselected": {"marker": {"opacity": 0}} } ] ), # 展示全部点 dict( method="restyle", label="展示全部", args=[ { "selectedpoints": None, "unselected": {"marker": {"opacity": 1}} } ] ) ] ) ] ) fig.show()
注意事项
- 布尔数组长度必须和散点图总数据点数量完全匹配,每个位置的布尔值对应相同索引点的显示状态
- 如果页面存在多个散点trace,可在args的第二个参数指定要生效的trace索引数组,示例:
args=[{属性配置}, [0, 2]]代表仅修改索引为0、2的两个散点trace - 另一种实现方式是把不同分组的点拆分为独立trace,通过修改trace的
visible属性控制显示,对应args写法为args=["visible", [True, False, False]],数组内布尔值按顺序对应每个trace的显示状态
内容的提问来源于stack exchange,提问作者Noa Be
相关产品推荐
相关产品推荐

