简体   繁体   中英

D3 Sankey Chord Colors

So I'm developing a Sankey diagram, using D3's Sankey API, and I'm trying to figure out how to change the color of the bands, or cords, going to and from the nodes. An example of what I'm trying to do can be found here:

http://tamc.github.io/Sankey/

I want to be able to individually choose each band and choose that individual band's color. I can't find any documentation for D3's Sankey API so I have no idea how to actually pull this off. I tried the setColors function that I found by searching through the code of the Sankey in the link that I provided. However, that doesn't seem to work with my code. I started my Sankey off using this code as a base:

http://tamc.github.io/Sankey/examples/simple.html

Can someone please give me an idea of how to change the color of a band using this as a reference?

PS If someone could also fill me in on how to change the color of a node, as well, that would be great!

The example you've linked to uses a different API on top of the Sankey plugin. I'll explain for this example . The Sankey plugin doesn't draw the visual elements, it only computes their positions, so you're free to set the colors as you like.

The relevant code for the links in the example is this:

var link = svg.append("g").selectAll(".link")
  .data(energy.links)
  .enter().append("path")
  .attr("class", "link")
  .attr("d", path)
  .style("stroke-width", function(d) { return Math.max(1, d.dy); })
  .sort(function(a, b) { return b.dy - a.dy; });

To change the color, simply set either a different class or set stroke explicitly:

.style("stroke", "red")

This can of course be a function as well so that you can set different colors for different paths. The nodes are similar:

node.append("rect")
  .attr("height", function(d) { return d.dy; })
  .attr("width", sankey.nodeWidth())
  .style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
  .style("stroke", function(d) { return d3.rgb(d.color).darker(2); })

In the example, the fill color is set based on the name -- you can adjust this as you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM