问题
I'm trying to work out how I can use multiple conditions with ternary operator in D3 (still finding my way with D3). I have a spreadsheet with a column legislative and the values included are Yes1, Yes2, Yes3 and No. For Yes1 I want to color my circles red, Yes2 are pink, Yes3 are orange and No are grey. The code below colors all circles either red or pink only.
.style("fill", function(d) {
return (d.data.legislative == "Yes1" ? "red" : "grey" || "Yes2" ? "pink" : "grey" || "Yes3" ? "orange" : "grey");
})
回答1:
In D3 it is convention to use a scale for this type of mapping between two sets of values.
In your case, you would create an ordinal scale, such as:
let colour = d3.scaleOrdinal()
.domain(["Yes1", "Yes2", "Yes3", "No"])
.range(["red", "pink", "orange", "grey"])
and then in your style function you would use the colour scale to return the colour based on the value of d.data.legislative:
.style("fill", function(d) { return colour(d.data.legislative) })
回答2:
The idiomatic D3 for this is using a simple ordinal scale, as stated in the other answer.
However, just for completeness, this is the correct ternary operator in your case:
return d.data.legislative === "Yes1" ? "red" :
d.data.legislative === "Yes2" ? "pink" :
d.data.legislative === "Yes3" ? "orange" : "gray";
Let's see it in action:
["Yes1", "Yes2", "Yes3", "No"].forEach(function(d) {
console.log(d + " -> " + (d === "Yes1" ? "red" : d === "Yes2" ? "pink" : d === "Yes3" ? "orange" : "gray"));
})
来源:https://stackoverflow.com/questions/51072989/using-ternary-in-d3