javascript - 为什么 d3js scaleTime 直方图中有最后一个无用的 bin?

标签 javascript d3.js

我有一个日期列表,我试图让容器代表一周中的每一天,以便绘制直方图。 结果有点像我想要的,但是最后一个 bin 有 x0=x1,因此总是空的。 为什么 bin 数组有 8 个元素,而我想要 7 个?

我试图阅读文档,但在提供的示例中似乎存在相同的问题

这是我使用的代码:

  const monday = new Date(2021, 4, 3)  // Monday 3 May 2021, midnight
  const next_monday =  new Date(2021, 4, 10)

  const scale = d3.scaleTime()
      .domain([monday, next_monday])

  const bins = d3.histogram()
      .domain(scale.domain())
      .thresholds(scale.ticks(7))

  console.log(
      bins([
          new Date(2021, 4, 3, 15), // 15h, monday
          new Date(2021, 4, 9, 15) // 15h, sunday, end of week
      ])
  )
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

结果是什么样的:

0: Array [ Date Mon May 03 2021 15:00:00 GMT+0200 (heure d’été d’Europe centrale) ]
    x0: Date Mon May 03 2021 00:00:00 GMT+0200 (heure d’été d’Europe centrale)
​​    x1: Date Tue May 04 2021 00:00:00 GMT+0200 (heure d’été d’Europe centrale)
​​1: Array []
​2: Array []
​3: Array []
​4: Array []
​5: Array []
​6: Array [ Date Sun May 09 2021 15:00:00 GMT+0200 (heure d’été d’Europe centrale) ]
​7: Array []
​​length: 0
​​    x0: Date Mon May 10 2021 00:00:00 GMT+0200 (heure d’été d’Europe centrale)
​​    x1: Date Mon May 10 2021 00:00:00 GMT+0200 (heure d’été d’Europe centrale)
    !!! x1=x0 !!! Why is this bin added ?
​​    <prototype>: Array []
​
length: 8

最佳答案

I have 8 time points, scale.ticks(7) is returning an array of 8 elements.

scale.ticks(7) 不一定返回具有 7 个刻度的数组:“指定的计数只是一个提示;比例可能会返回更多或更少的值,具体取决于域。” from the docs .量表优先考虑“合理的值(例如每天午夜)”

那个午夜部分正在摆脱你的蜱虫:它是蜱虫的自然场所,给你 8 个蜱虫,每个星期一一个。相反,您可以修改您的域以避免该问题:

 const next_monday =  new Date(2021, 4, 10)-1  // just before midnight.

刻度保证在域内,所以你不应该看到那个刻度:

const monday = new Date(2021, 4, 3)  // Monday 3 May 2021, midnight
  const next_monday =  new Date(2021, 4, 10)-1

  const scale = d3.scaleTime()
      .domain([monday, next_monday])

  const bins = d3.histogram()
      .domain(scale.domain())
      .thresholds(scale.ticks(7))

  console.log(
      bins([
          new Date(2021, 4, 3, 15), // 15h, monday
          new Date(2021, 4, 9, 15) // 15h, sunday, end of week
      ])
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - 为什么 d3js scaleTime 直方图中有最后一个无用的 bin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67402682/

相关文章:

javascript - 弹出消息框打开时如何卡住屏幕的其余部分

java - 什么相当于 Android/Java 中的 JavaScript setInterval/setTimeout?

d3.js - D3.js 是 Neo4j Graph DB 数据实时可视化的正确选择吗

d3.js - 如何在 D3.js 中制作多个组网络节点的凸包

javascript - 如何在点击时启动计时器?

javascript - 在 A-Frame 组件上,如何在函数之间共享数据?

javascript - 使用 Javascript Ajax 将较长的 html 发布到 ASP.NET 页面时找不到页面

javascript - d3 — 逐步绘制大型数据集

javascript - 带 x+y 轴的 d3js 条形图 : x axis value distribution

javascript - 文本和输入元素以相同的方式附加和赋予属性。显示文本但不显示输入。为什么?