This is a fork of Mike Bostock's Multi-Series Line Chart, which adds circles along the line for each data point. The circles help anchor us to the real datapoints (rather than extrapolations) when comparing across lines.
But this is really an exercise in nested selections, leveraging selections as groups. The data consists of multiple lines, which each have multiple data points. We call .data
twice: first with the data for all cities, binding the array for each city as a single datum. This is good enough for D3's line generators but not for placing circles. So we selectAll circles from the merged enter-update selection, and then bind the data for each line using a function, which is passed each datum from the prior join. This step produces a new data join, and you need to do it even if the function you pass is the identity. Since there are no circles, we skip straight to the enter selection and append them. Then we assign them x and y positions based on the accessors for the line generator.
But how do we get the color? Functions passed to .attr
and .style
as second arguments receive the datum d
, the index i
, and a little-known third argument j
. It turns out that i
is the index within the group (which point on the line) while j
is the index of the group (which line of the three). We use j
to index into our original data and determine the color of the point.
All of this happens in the last "paragraph" of the code. Selection groups are fully explained in How Selections Work, which is required reading for mastery of D3.
Hello Max, thanks for this.
Question: Your example is done in d3 v3 where "j" is the index, how would you implement with d4?
Thanks
Jerry