Javascript D3 直方图 : thresholds producing wrong number of bins

标签 javascript d3.js histogram data-visualization

我正在使用 D3 创建直方图 JS 脚本,一切似乎都正常工作……除了 bin 的数量。

以下是我的代码的相关部分:

//Define the scales for the x and y attributes
var x = d3.scaleBand()
    .range([0, width])
    .padding(configProperties.barPadding);
var y = d3.scaleLinear()
    .range([height,0]);

//Create the bins
var bins = d3.histogram()
    .domain(d3.extent(data))
    .thresholds(configProperties.binsCount)
    (data);

console.log("number of bins: " + bins.length); //9
console.log("intended number of bins: " + configProperties.binsCount); //10

如果我将 configProperties.binsCount 设置为 9,bins.length 仍然是 9。 如果我将 configProperties.binsCount 设置为 14,bins.length 仍然是 9。

但是,如果我将 binsCount 设置为 15 或更高... bins.length 输出 23。

我对 histogram.thresholds 如何工作的理解基于 the documentation是如果我给它一个值,它会将数据分成那么多 + 1 个相等的段(即那么多的箱子)。但是,它似乎根本没有这样做。我能找到的所有示例代码似乎都表明我正在正确使用它,但我无法获得所需的 bin 数量。

我也试过使用 d3.ticks作为阈值参数,但我遇到了同样的问题。

有什么我想念的吗?跟我的域名有关系吗?提前致谢。

最佳答案

您正在向thresholds 函数传递一个计数(即一个简单的数字),不是数组。

您看到的是传递数字时的预期行为。根据same docs :

If a count is specified instead of an array of thresholds, then the domain will be uniformly divided into approximately count bins;

让我们在这个演示中看看:

var data = d3.range(100);

const histogram = d3.histogram()
  .value(d => d)
  .thresholds(5);

var bins = histogram(data);

console.log("The number of bins is " + bins.length)
<script src="https://d3js.org/d3.v4.js"></script>

可以看到,count为5,bin的个数也为5。

但是,如果您传递一个数组,行为就是您所期望的:bin 的数量将为array.length + 1:

Thresholds are defined as an array of values [x0, x1, …]. Any value less than x0 will be placed in the first bin; any value greater than or equal to x0 but less than x1 will be placed in the second bin; and so on. Thus, the generated histogram will have thresholds.length + 1 bins.

这是演示:

var data = d3.range(100);

const histogram = d3.histogram()
  .value(d => d)
  .thresholds([10, 30, 50, 70, 90]);

var bins = histogram(data);

console.log("The number of bins is " + bins.length)
<script src="https://d3js.org/d3.v4.js"></script>

如您所见,数组有 5 个值,bin 数为 6。

最后,请记住,bin 的实际数量取决于您传递给直方图生成器的数据。这解释了您在问题中描述的其他结果。

关于Javascript D3 直方图 : thresholds producing wrong number of bins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380637/

相关文章:

javascript - 如何动态设置工具提示宽度?

R ggplot scale_fill_gradient2 直方图与点图

c - 直方图生成函数

javascript - Primefaces 单页上的多个 Highcharts 出现 JavaScript 错误

javascript - 根据 JavaScript 的 Parent Id 将对象设为子对象

javascript - jQuery 选项卡小部件显示问题

javascript - 如何将 JS Flow 类型与 Redux reducer 和 lodash 结合使用?

javascript - 在 d3 路径内添加数字/文本

Javascript OOP,getters,setters,运行 - D3.js - 通过选项设置使图表可重新使用

matlab - 直方图产生的值低于预期