简体   繁体   中英

Using ternary in D3

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");
})

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) })

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")); }) 

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