Rainbow Worm color change

I am using Mike Bostocks Rainbow Worm as part of my project. https://bl.ocks.org/mbostock/4165404

I am trying to change the color of the worm as it will represent the wind speed in the project. The coloring is described by this function:

var path = svg.selectAll("path")
.data(quad(points))
.enter().append("path")
.style("fill", function(d) { return d3.hsl(z(d[1].value), 1, .5); })
.style("stroke", "#000");

      

If you replace function (d) with "color", the worm will be one-color. How can I make the parts of the worms colored red-> white-> red-> white-> red-> white, etc.

+3


source to share


1 answer


Use index (second parameter) and remainder operator :

.style("fill", function(d,i) { return i%2 ? "red" : "white" })

      

This is what this snippet does:

The second parameter, referred to here i

, is the index of each data item, from 0 to data.length - 1

.

Then, using the remainder operator ...



i % 2

      

... we get a series of zeros and ones:

010101010101010101...

      

As in JavaScript (and in all languages ​​I know of) 0 is false, the tertiary operator alternately returns "white" and "red".

Here is bl.ocks: http://bl.ocks.org/anonymous/fd5c1e6644d742e43c737ff4a17f96ff

+2


source







All Articles