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

D3.js多线图圆点(symbol)颜色赋值异常问题求助

问题原因

你使用的是D3 v3版本的旧API写法,v4及更高版本中,元素回调函数的第三个参数已不再是父级分组的索引,而是当前选中的所有同层级节点集合,因此你拿到的j是全部circle元素组成的数组,符合新版本的API行为。

解决方案

方案1:给子数据附加父级属性(推荐,性能更好)

在给circle绑定数据时,直接把父级gameb对应的name属性嵌入到子数据中,无需额外查询节点:

gameb.selectAll("circle")
     // 遍历每个父级的values,附加父级name
     .data(function(d) {return d.values.map(item => Object.assign({}, item, {parentName: d.name}));})
     .enter()
     .append("circle")
     .attr("cx", function(d) {return x(d.date);})
     .attr("cy", function(d) {return y_count(d.count);})
     .attr("r", 3)
     // 直接从子数据取父级name取色即可
     .style("fill", function(d) {return color(d.parentName);});

方案2:查询父节点绑定的数据

如果不想修改原始数据结构,可以通过当前circle的父节点获取绑定的父级数据:

gameb.selectAll("circle")
     .data(function(d) {return d.values;})
     .enter()
     .append("circle")
     .attr("cx", function(d) {return x(d.date);})
     .attr("cy", function(d) {return y_count(d.count);})
     .attr("r", 3)
     .style("fill", function(d) {
       // 获取当前circle的父级g元素绑定的数据
       const parentGame = d3.select(this.parentNode).datum();
       return color(parentGame.name);
     });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:57:02