我如何改变颜色的路径在D3.js

How do I change the color of path in D3.js?

本文关键字:D3 js 路径 何改 变颜色      更新时间:2023-09-26

我在D3的树形图中创建了一些路径,我想改变线(路径)的颜色,但我不能使我的代码工作:

 // Enter any new links at the parent's previous position.
      link.enter().insert("svg:path", "g")
          .attr("class", "link")
          .attr("d", function(d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal({source: o, target: o});
          })
        .transition()
          .duration(duration)
          .attr("d", diagonal);
      // Transition links to their new position.
      link.transition()
          .duration(duration)
          .attr("d", diagonal);
      // Transition exiting nodes to the parent's new position.
      link.exit().transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            return diagonal({source: o, target: o});
          })
          .remove();

我试着用下面的方法来改变,我已经查找了一些其他的解决方案,但我真的不明白我需要在我的更新选择中选择什么来改变它。

  link.selectAll("path")
      .attr("stroke", "#000000");

提前感谢您的帮助

我自己刚开始使用d3,但我认为你需要使用link.style("stroke",#xxxxxx)

svg可以通过使用fill属性来改变颜色(对于path属性来说同样复杂,即使它是svg的子属性)

  svg
    .data([newValue])
    .transition()
    .duration(1500)
    .attr('fill', function(d) { return color(d); })

工作代码供参考:
https://jsfiddle.net/pjrc0yy3/1/