如何获得d3.js中数据集中给定范围之间的最小值和最大值

时间:2018-06-08 13:23:38

标签: d3.js crossfilter

我有一个格式为的数据集:

[{
  x: "2014-01-01",
  y: 1223 
},
 ...
 {x: "2017-01-01",
  y: 143
 }
 ];

并给出范围例如

["2015-01-01","2016-01-01"]

我想找到这两个范围之间的最小和最大y值。

我怎样才能在d3中这样做?

目前,我使用以下函数来查找min / max

d3.min(formattedData, function(d) { return d.y; }), 

d3.max(formattedData, function(d) { return d.y; });

我不确定如何在那里应用范围

已经解析了日期,所以不要担心该部分

我在所有x值上应用以下函数,即。 parseDate.parse(x)的

parseDate = d3.time.format('%Y-%m-%d');

2 个答案:

答案 0 :(得分:2)

您可以过滤阵列中的元素以适应您需要的日期范围:

inputArray.filter(d => d.x > "2015-01-01" && d.x < "2016-01-01")

然后,您可以映射(转换)过滤后的元素,将它们转换为相关的y值:

.map(d => d.y)

最终获得结果数组的最小值或最大值:

d3.min(..)

给出:

&#13;
&#13;
var input = [
  {
    x: "2014-01-01",
    y: 1223 
  },
  {
    x: "2015-06-01",
    y: 12
  },
  {
    x: "2015-07-01",
    y: 1025
  },
  {
    x: "2015-08-01",
    y: 125
  },
  {
    x: "2017-01-01",
    y: 143
  }
 ]

var output = input
  .filter(d => d.x > "2015-01-01" && d.x < "2016-01-01")
  .map(d => d.y);

console.log("filter/map array: " + output);
console.log("min: " + d3.min(output));
console.log("max: " + d3.max(output));
&#13;
<script src="https://d3js.org/d3.v5.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果您的列表非常长并且您不想多次循环,则可以在一次通话中完成此操作:

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  <script>
    var input = [{
        x: new Date("2014-01-01"),
        y: 1223
      }, {
        x: new Date("2015-06-01"),
        y: 12
      }, {
        x: new Date("2015-07-01"),
        y: 1025
      }, {
        x: new Date("2015-08-01"),
        y: 125
      }, {
        x: new Date("2017-01-01"),
        y: 143
      }],
      minDate = new Date("2015-01-01"),
      maxDate = new Date("2016-01-01");

    var minMax = d3.extent(input, function(d) {
      if (d.x <= minDate || d.x >= maxDate){
        return NaN;
      }
      return d.y;
    })
    console.log(minMax);
  </script>
</body>

</html>
&#13;
&#13;
&#13;