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

如何获取Plotly点击点的customdata属性?及属性使用正确性咨询

如何在Plotly点击事件中获取点的text或customdata属性

嘿,关于Plotly点击事件获取自定义属性的问题,我可以帮你梳理清楚,顺带修正下你代码里的小问题~

首先,你的customdata属性位置放错啦!customdata是trace级别的属性,应该和x、y、text这些属性同级,而不是嵌套在marker里面。放在marker里的话,Plotly不会把它绑定到点的属性集合中,自然在点击事件里拿不到。

修正后的Trace代码

var trace = {
  x: [5],
  y: [7],
  name: 'example',
  hovertemplate: '%{text}',
  text: ['example'],
  mode: 'markers',
  visible: 'legendonly',
  customdata: ['https://google.com/'], // 移到这里,和x/y同级
  marker: {
    size: [257],
    sizeref: 2,
    sizemode: 'area',
    opacity: 0.3
  }
};

获取点击点的text和customdata

当你正确设置属性后,通过plotly_click事件就能轻松拿到这些信息。在事件回调中,event.points数组包含了所有被点击的点(单个点击时数组只有一个元素),每个点对象里就有你需要的text、customdata,还有坐标等属性:

// 假设你的图表容器id是"my-plot"
document.getElementById('my-plot').on('plotly_click', function(event) {
  if (event.points.length > 0) {
    const clickedPoint = event.points[0];
    console.log('点击点的text:', clickedPoint.text);
    console.log('点击点的customdata:', clickedPoint.customdata);
    // 还能拿到其他属性,比如坐标
    console.log('点击点X坐标:', clickedPoint.x);
    console.log('点击点Y坐标:', clickedPoint.y);
  }
});

补充说明

  • 如果是框选多个点,event.points会包含所有选中的点,你可以遍历数组处理每个点的属性;
  • text属性同理,只要在trace里正确定义,就能在clickedPoint.text中获取到;
  • 除了text和customdata,你还能拿到点的name、marker样式等几乎所有在trace中定义的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:35:05