javascript - 了解阈值尺度中的 invertExtent

标签 javascript d3.js

我正在研究 Mike Bostock 的等值线图(慢慢地),并在我去的时候写下每一点以确保我理解它。我特别难以理解一点。该示例在线:https://bl.ocks.org/mbostock/4060606

在代码中的某一点,Bostock 有一系列颜色,并且正在将它们的倒数范围(如果输入到色标中将产生该颜色的最小值和最大值)添加到 map 中。对于每个“d”(这是一个包含两种颜色的数组),他使用 color.invertExtent(d) 来获取最小值和最大值。在该函数的末尾,他将“d”值(现在是两个数字的数组,最小值和最大值)返回到 map 。这个我明白了。

g.selectAll("rect")
  .data(color.range().map(function(d) {
      d = color.invertExtent(d);
      if (d[0] == null) d[0] = x.domain()[0];
      if (d[1] == null) d[1] = x.domain()[1];
      return d;
    }))

但是,他还包括两个我不理解的“if” block 。为什么需要它们?为什么这个双色数组的 d[0] 或 d[1] 永远等于“null”?为什么他将它们分配给 x.domain[0](在本例中为 600)和 x.domain[1],即 860。在什么情况下结果甚至会是“null”?

最佳答案

这实际上在文档中有描述。如果你看threshold.invertExtent ,你会看到:

Returns the extent of values in the domain [x0, x1] for the corresponding value in the range, representing the inverse mapping from range to domain. This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. For example:

var color = d3.scaleThreshold()
    .domain([0, 1])
    .range(["red", "white", "green"]);

color.invertExtent("red"); // [undefined, 0]
color.invertExtent("white"); // [0, 1]
color.invertExtent("green"); // [1, undefined]

你看到那些 undefined 了吗?它们是范围的第一个和最后一个值的正确预期。

问题是,对于矩形的输入选择,您不能使用具有 undefinednull 的数组(undefined == nulltrue)。所以,那些 if 所做的就是转换这个数组:

[[undefined,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9, undefined]]

进入这个:

[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10]]

这是一个现场演示。首先,没有 if:

var scale = d3.scaleThreshold()
  .domain(d3.range(1, 9, 1))
  .range(d3.range(9));

console.log(scale.range().map(function(d) {
  d = scale.invertExtent(d);
  return d;
}))
<script src="https://d3js.org/d3.v4.min.js"></script>

现在和他们一起:

var scale = d3.scaleThreshold()
  .domain(d3.range(1, 9, 1))
  .range(d3.range(9));

console.log(scale.range().map(function(d) {
  d = scale.invertExtent(d);
  if (d[0] == null) d[0] = 0;
  if (d[1] == null) d[1] = 9;
  return d;
}))
<script src="https://d3js.org/d3.v4.min.js"></script>

最后,真正理解这一点的关键是理解阈值量表的工作原理。这是最重要的部分,注意元素个数:

If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. If there are fewer than N elements in the domain, the additional values in the range are ignored. If there are more than N elements in the domain, the scale may return undefined for some inputs.

关于javascript - 了解阈值尺度中的 invertExtent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48161257/

相关文章:

javascript - 在 Flickr API 的 Tags 参数内传递变量

javascript - 有人可以提供如何在 Ember.js 中定义自定义事件的示例吗?

javascript - 不区分大小写的正则表达式快速检查

javascript - 如何将节点从一个模拟移动到另一个模拟

d3.js - 如何重置/清除 d3-brush?

javascript - D3.js 比例 : Return the smaller of a constant and the value of a scale?

javascript - angularjs日期选择器实现错误

javascript - 事件监听器 JavaScript

graph - D3 : Force Layout with fixed Y ranges - Reducing link overlap

node.js - Node js、NVD3.js无法读取未定义的属性baseval