Reputation: 1425
So I am drawing a tree (somewhat similar to a decision tree) with D3.js, using a premade template I found online. My goal at this point is to color the edges (or links
) according to a property of each link
object.
My first step was to color all the edges regardless of their property, so I added the following line:
// Update the links…
var link = svgGroup.selectAll("path.link")
.data(links, function(d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
//.style("stroke", "red") ---- this new line changes the color of all links
.attr("d", function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
});
Now, I want to color them according to their property. It is accessible through the first link
initialization:
// Update the links…
var link = svgGroup.selectAll("path.link")
.data(links, function(d) {
// const booleanProperty = d.target.colorProperty; --- change color according to this property
return d.target.id;
});
My thought was to create 2 different variables - one storing the links with the property set to true
and another with the property set to false
, so I could change the color of each link
group. Somewhat like this:
// Update the links…
var trueLink = svgGroup.selectAll("path.link")
.data(links, function(d) {
const booleanProperty = d.target.colorProperty; --- change color according to this property
if (booleanProperty) return d.target.id;
});
var falseLink = svgGroup.selectAll("path.link")
.data(links, function(d) {
const booleanProperty = d.target.colorProperty; --- change color according to this property
if (!booleanProperty) return d.target.id;
});
This attempt didn't work, since selectAll("path.link")
returns all the links regardless if there is a condition to return only in specific cases. I also tried using select("path.link")
, but I got exactly the same result.
Is there a way I can pull this off?
Upvotes: 0
Views: 135
Reputation: 81
I assume that you want to set that style in the "enter" selection for new items, so you could try to do the condition inside the .style call, something like this:
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.style("stroke", function(d) { return condition ? "red" : "blue"; } )
.attr("d", function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
});
Where "condition" may be anything you need. If the condition or the color is stored in the datum, you can return d.target.colorProperty or use it for the condition.
Upvotes: 1