javascript 在 d3 序数尺度中映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17321139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping in d3 ordinal scales
提问by neoeahit
I am using D3's ordinal scale, to map numbers to color. I have used this:
我正在使用 D3 的序数比例,将数字映射到颜色。我用过这个:
color = d3.scale.ordinal().range(["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2"]).domain([0,6]);
console.log(color(0),color(1),color(2),color(3),color(4),color(5),color(6));
The response I am getting is:
我得到的回应是:
#1f77b4 #2ca02c #d62728 #9467bd #8c564b #e377c2 #ff7f0e
#1f77b4 #2ca02c #d62728 #9467bd #8c564b #e377c2 #ff7f0e
I am curious shouldn't the response be:
我很好奇不应该是这样的回应:
#1f77b4, #ff7f0e, #2ca02c, #d62728, #9467bd, #8c564b, #e377c2
#1f77b4, #ff7f0e, #2ca02c, #d62728, #9467bd, #8c564b, #e377c2
Please advise.
请指教。
回答by Adam Pearce
The domain isn't quite right:
域不太正确:
> color.domain()
[0, 6, 1, 0.5]
For each value in an ordinal scale'srange, there should to be a matching value in the domain.
对于序数范围内的每个值,域中都应该有一个匹配值。
Instead of setting the domain to [0,6]
, it should be [0, 1, 2, 3, 4, 5, 6]
:
而不是将域设置为[0,6]
,它应该是[0, 1, 2, 3, 4, 5, 6]
:
color = d3.scale.ordinal()
.range(["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2"])
.domain(d3.range(0,7));
Checking to make sure everything works after updating color:
检查以确保更新颜色后一切正常:
> d3.range(0,7).forEach(function(d){ console.log(color(d)); })
#1f77b4
#ff7f0e
#2ca02c
#d62728
#9467bd
#8c564b
#e377c2
回答by Andy Thornton
This is expected as there are only 2 explicitly defined values in your domain. So the first value of 0 is assigned to the first color of #1f77b4
, the second value of 6 is assigned to the second color,#ff7f0e
, and the remainders are inferred after they are sorted internally as strings. You need to define the domain explicitly for predictable behavior. For example,
这是意料之中的,因为您的域中只有 2 个明确定义的值。所以第一个值 0 分配给 的第一种颜色#1f77b4
,第二个值 6 分配给第二种颜色 ,#ff7f0e
余数在内部作为字符串排序后推断出来。您需要为可预测的行为明确定义域。例如,
color = d3.scale.ordinal()
.range(["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2"])
.domain([0,1,2,3,4,5,6]);
console.log(color(0),color(1),color(2),color(3),color(4),color(5),color(6));
As the documentationstates
正如文档所述
Setting the domain on an ordinal scale is optional. If no domain is set, each unique value that is passed to the scale function will be assigned a new value from the output range; in other words, the domain will be inferred implicitly from usage. However, it is a good idea to assign the ordinal scale's domain to ensure deterministic behavior, as inferring the domain from usage will be dependent on ordering.
按序数设置域是可选的。如果未设置域,则传递给 scale 函数的每个唯一值都将从输出范围中分配一个新值;换句话说,域将根据用法隐式推断。但是,分配序数尺度的域以确保确定性行为是一个好主意,因为从使用情况推断域将取决于排序。