Reputation: 1
I want to change d3 sankey node color. This is data sampledata-sample and I tried below coding but it didnt work;
color = d3.scaleOrdinal()
.domain(["A","B","C","D","E","F",])
.range(["#FD3E35","#FFA500","#0000FF","#00ff00","#bee0e6","#bec2e6"]);
with below code,
.style("fill", function (d) {
return d.color = color(d.name.replace(/ .*/, ""));
})
My first question what is the function of this coding? d.name.replace(/ ./, "")*
Also can i change the color of nodes with my csv document with adding a column "color"?
Upvotes: 0
Views: 167
Reputation: 338
First off, in your data sample there's no column with the name "name", so d.name is actually undefined
. I'm going to guess you want to set the color depending on the source (you can change it for target if you want).
To do this, your color function is correct, however your call needs to be changed to use d.source
instead of d.name
.
.style("fill", (d) => color(d.source.replace(/ .*/, "")))
What .replace(/ .*/, "")
is doing here, is replacing everything mathced by the regular expression / .*/
with an empty string ""
. However, that specific regular expression means that everything after and including the first whitespace " "
will be removed. So if your string would be "Hello, World!"
, the string returned by that replace would be "Hello,"
If this isn't an issue for your data, you could just do:
.style("fill", (d) => color(d.source))
Regarding your last question, you can use a column with the color to be used for every link. To do this you need to be careful that the color put is either an accepted CSS color name or a HEX color code. If this would be the case, your data should have the color in the object passed by d3, so you can use:
.style("fill", (d) => d.color)
Upvotes: 1