gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:33:29 26 4
gpt4 key购买 nike

我有一个日期列表,我试图让容器代表一周中的每一天,以便绘制直方图。结果有点像我想要的,但是最后一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com