Home > OS >  d3.js: Multiple Series Line Chart
d3.js: Multiple Series Line Chart

Time:09-19

With this code as a starting point: Parsed / processed data

The axes appear to be reasonable: For the X-axis, I'm taking the "since_midnight" value, pulling the extents, and formatting it as a time. The Y-axis, similarly, is just the extents of the "margin" value. I get this -- so far so good:

enter image description here

Next, I want to add some lines to my chart. My thinking is that I iterate through the map, and for each of the map elements, I add the element as data to a series. What I get is a gigantic "Nothing Happens" though. No lines, no errors, just "Gosh, your data looks great, but I'm going to ignore it."

//line generator?
var valueline = d3.line()
  .x(function(d) { return x(d.since_midnight); })
  .y(function(d) { return y(d.margin); });
  
group_by_sailing_date.forEach(function (s) {
  svg_summ.append("path")
    .data(s)
    .attr("stroke", "steelblue")
    .attr("stroke-width", "3px")
    .attr("d", valueline);
});

I feel like I'm missing something really fundamental here, but I'm drawing a complete blank (pun intended, ha ha ha). Help?

CodePudding user response:

Ok, I've made it work, but I don't know why. I removed the .data(s) line, and changed "valueline" to "valueline(s)". No idea why this works. Technically, it's all good, but I'd be thrilled if someone could help me understand what this code actually means.

group_by_sailing_date.forEach(function (s) {
 svg_summ.append("path")
  .attr("stroke", "steelblue")
  .attr("fill", "none")
  .attr("stroke-width", "1px")
  .attr("d", valueline(s));

});

CodePudding user response:

Following the rules of selection within d3.js (https://bost.ocks.org/mike/selection/) the code should look something like this:

svg_summ.selectAll("path")
  .data(group_by_sailing_date)
  .enter()
    .append("path")
      .attr("stroke", "steelblue")
      .attr("fill", "none")
      .attr("stroke-width", "1px")
      .attr("d", (d) => valueline(d));
  • Related