Search code examples
javascriptd3.jsternary

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

Solution

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