You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码触发Plotly.js预定义选框的点选中事件?

解决方法

1. 调用Plotly内置选点方法(适配Plotly场景)

如果你用的是Plotly.js,预定义在layout.shapes里的矩形选框不会自动触发点识别,直接调用内置方法就能触发和手动框选一致的逻辑:

  • 先获取图表实例:

    const chart = Plotly.d3.select('#你的图表ID').node();
    
  • 接着调用选点计算方法,传入所有预定义选框:

    const shapes = chart.layout.shapes;
    Plotly.Plots._selectPoints(chart, {
      type: 'box',
      shapes: shapes
    });
    

    这个方法会自动遍历所有选框,计算并更新选中点数组(chart.data[i].selectedpoints),同时触发plotly_selected事件。

2. 初始化时自动执行

把这段逻辑放在图表渲染完成的回调里,比如Plotly.newPlot的then回调:

Plotly.newPlot('你的图表ID', 数据, 布局配置).then(() => {
  const chart = Plotly.d3.select('#你的图表ID').node();
  const shapes = chart.layout.shapes;
  Plotly.Plots._selectPoints(chart, {
    type: 'box',
    shapes: shapes
  });
});

3. 手动计算选点(内置方法不适用时)

如果内置方法不好用,也可以自己遍历数据点判断是否在选框内:

// 遍历每个数据系列
数据.forEach((trace, idx) => {
  const selectedPoints = [];
  // 逐个检查点的坐标
  trace.x.forEach((x, i) => {
    const y = trace.y[i];
    // 判断是否在任意一个矩形选框里
    const isInShape = 布局配置.shapes.some(shape => {
      if (shape.type !== 'rect') return false;
      // 处理x0/x1、y0/y1可能顺序颠倒的情况
      const xMin = Math.min(shape.x0, shape.x1);
      const xMax = Math.max(shape.x0, shape.x1);
      const yMin = Math.min(shape.y0, shape.y1);
      const yMax = Math.max(shape.y0, shape.y1);
      return x >= xMin && x <= xMax && y >= yMin && y <= yMax;
    });
    if (isInShape) selectedPoints.push(i);
  });
  // 更新当前系列的选中点
  trace.selectedpoints = selectedPoints;
});
// 刷新图表
Plotly.update('你的图表ID', 数据);

内容的提问来源于stack exchange,提问作者drypatrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:52:07