首页 > 解决方案 > 为什么 d3js scaleTime 直方图中有最后一个无用的 bin?

问题描述

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

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

这是我使用的代码:

  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

标签: javascriptd3.js

解决方案


我有 8 个时间点, scale.ticks(7) 返回一个包含 8 个元素的数组。

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

午夜的那部分让你的蜱虫消失了:这是一个自然的蜱虫地点,给你 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>


推荐阅读