Update the y-axis of a brushed area chart

后端 未结 2 510
既然无缘
既然无缘 2021-02-05 09:35

I am using d3.js, and I\'m working on a brushed area chart by modifying this example. In addition to the x-axis changing based on the brush, I\'d like chart\'s y-axis to be redr

相关标签:
2条回答
  • 2021-02-05 10:18

    I came up with a solution.

    I used the brush-filtered x.domain to filter down my original data set. This new filtered data set has only the values that fall within the brush:

    // Use x.domain to filter the data, then find the max and min duration of this new set, then set y.domain to that
      x.domain(brush.empty() ? x2.domain() : brush.extent());
      var dataFiltered = data.filter(function(d, i) {
        if ( (d.date >= x.domain()[0]) && (d.date <= x.domain()[1]) ) {
          return d.duration;
        }
      })
      y.domain([0, d3.max(dataFiltered.map(function(d) { return d.duration; }))]);
    

    Finally, be sure to redraw the y-axis as well as the x-axis:

    focus.select("path").attr("d", area);
    focus.select(".x.axis").call(xAxis);
    focus.select(".y.axis").call(yAxis);
    
    0 讨论(0)
  • 2021-02-05 10:36

    A shorter possibility would be to use d3.scale.invert() on your brush.extent() like so:

    var domainExtent = brush.extent().map(function(d){return scale.invert(d);});
    var filteredData = data.filter(function(d){return ((d <= domainExtent[1]) && (d >= domainExtent[0]));});
    

    However, by now d3 has gained d3.brushX(), which only allows brushing in East/West direction by design.

    0 讨论(0)
提交回复
热议问题