d3.js 序数 returns 一个错误的值

d3.js ordinal scale returns a wrong value

有人可以向我解释我做错了什么以及为什么 'B' 不是“50”而 'C' 变成“0”吗?

示例(咖啡脚本)

scale = d3.scale.ordinal().domain(['A', 'B', 'C']).range([0,100])

console.log scale.domain()
console.log scale.range()

console.log scale('A')
console.log scale('B')
console.log scale('C')

结果

["A", "B", "C"]
[0, 100]
0
100
0

example on jsfiddle

如果您在此处使用 range,则您定义了域值和范围值之间的一对一映射。见the docs,具体为:

"If there are fewer elements in the range than in the domain, the scale will recycle values from the start of the range."

这就是您的示例中发生的情况:C 被映射到与 A

相同的范围值

在这种情况下,您似乎应该改用 rangePoints。这将为您提供一个连续的间隔,细分为 n 个均匀分布的点,其中 n 是输入域中(唯一)值的数量.参见:

scale = d3.scale.ordinal().domain(['A', 'B', 'C']).rangePoints([0,100])

参见:http://jsfiddle.net/henbox/b0vktgjq/1/