如何通过customJS在NetworkD3中选中特定节点并修改其颜色
NetworkD3选中特定节点修改颜色实现方案
完全可以通过onRender注入自定义JS实现,不需要修改networkD3底层源码。
networkD3渲染的力导向图中,每个class为node的节点组下的circle元素就是节点图形,元素上绑定了对应节点的所有传入数据(Nodes数据框里定义的name/group/size等字段都可直接读取匹配),筛选到目标节点后直接修改fill样式属性即可。
固定修改指定节点颜色
如果需要提前指定某几个固定节点改色,直接在现有customJS里添加节点筛选逻辑即可,修改后的完整代码示例:
p <- forceNetwork(Links = links, Nodes = nodes, Source = 'source', Target = 'target', NodeID = 'name', Group = 'group', Value = "value", Nodesize = 'size', radiusCalculation = JS("d.nodesize/2"), zoom = TRUE, arrows = FALSE, linkWidth = JS("function(d){return d.value;}"), linkDistance = JS("function(d){return d.value*100}"), charge = gravity, opacity = 0.95, fontSize = 24, bounded = FALSE, linkColour = "#424242" ) customJS <- "function() { // 原有样式逻辑 d3.selectAll('.node text').style('fill', 'white').attr('stroke-width', '.1px').attr('stroke', '#3f3f3f'); d3.select('body').style('background-color', '#15171A'); // 新增指定节点改色逻辑 const targetNodeName = '替换为你要选中的节点name值'; const targetColor = '#FF4500'; // 替换为目标节点颜色 d3.selectAll('.node circle') .filter(function(d) { return d.name === targetNodeName; }) .style('fill', targetColor) .style('stroke', targetColor); // 原有力导向模拟预计算逻辑 simulation = this; simulation.stop(); for (var i = 0; i < 300; ++i) simulation.tick(); simulation.restart(); }" g <- htmlwidgets::onRender(p, customJS)
- 匹配规则可根据需求灵活调整:
- 按节点索引匹配:
.filter(function(d) { return d.index === 2; })选中第3个节点(索引从0开始计数) - 按分组匹配:
.filter(function(d) { return d.group === '核心组'; })选中所有属于核心组的节点 - 多条件匹配:
.filter(function(d) { return d.size > 10 && d.group === 'A'; })选中size大于10且属于A组的节点
- 按节点索引匹配:
点击选中节点改色(交互模式)
如果需要点击节点触发高亮、再次点击恢复原色的交互效果,可将customJS替换为以下版本:
customJS <- "function() { d3.selectAll('.node text').style('fill', 'white').attr('stroke-width', '.1px').attr('stroke', '#3f3f3f'); d3.select('body').style('background-color', '#15171A'); // 点击选中高亮逻辑 const highlightColor = '#FF4500'; d3.selectAll('.node circle') .on('click', function() { const currentNode = d3.select(this); if(currentNode.style('fill') === highlightColor) { // 恢复分组默认颜色 currentNode.style('fill', function(d) { return color(d.group); }) .style('stroke', function(d) { return color(d.group); }); } else { // 设置为高亮色 currentNode.style('fill', highlightColor) .style('stroke', highlightColor); } }) simulation = this; simulation.stop(); for (var i = 0; i < 300; ++i) simulation.tick(); simulation.restart(); }"
注意:如果没有自定义
colourScale参数,networkD3默认分组色阶的变量名就是color,上述恢复默认颜色的逻辑可直接生效;如果自定义了色阶,把代码里的color替换为自定义色阶的变量名即可。
内容的提问来源于stack exchange,提问作者Higor Augusto Gomes
相关产品推荐
相关产品推荐

