简体   繁体   English

d3线性色标输出错误

[英]d3 linear color scale output is wrong

I have the following function: 我有以下功能:

function getColor(value){
    //value from 0 to 1
    var color = d3.scale.linear()
    .domain([0, 1])
    .range(colorbrewer.Greys[9]);

    console.log(value + " = > " + color(value));

    return color(value);
}

This uses the colorbrewer.js from D3. 这使用了D3中的colorbrewer.js

However, the values returned are off. 但是,返回的值是关闭的。

For example I get: 例如我得到:

1 = > #f0f0f0 and 0 = > #ffffff which happen to be the first and second in the scale: 1 = > #f0f0f00 = > #ffffff 1 = > #f0f0f0 ,它们恰好是刻度的第一和第二:

["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]

How can I make it interpolate so that it calculates the right color based on a value between 0 and 1? 如何进行插值,以使其基于0到1之间的值计算正确的颜色? I also tried the ordinal scale, but that didn't help much either. 我也尝试过按序刻度,但这也无济于事。

What you really want to do is use quantize scales 您真正想做的是使用量化比例

Quantize scales are a variant of linear scales with a discrete rather than continuous range. 量化刻度是线性刻度的一种变体,具有离散范围而不是连续范围。 The input domain is still continuous, and divided into uniform segments based on the number of values in (the cardinality of) the output range. 输入域仍然是连续的,并且根据输出范围(的基数)中的值的数量分为均匀的段。

Consider this plunker : 考虑一下这个矮子

where the key is: 关键是:

function getColor(value){
    //value from 0 to 1
    var color = d3.scale.quantize()
    .domain([0, 1])
    .range(colorbrewer.Greys[9]);

    console.log(value + " = > " + color(value));

    return color(value);
}

Quoting the documentation : 引用文档

The array must contain two or more values, to match the cardinality of the input domain, otherwise the longer of the two is truncated to match the other. 该数组必须包含两个或多个值,以匹配输入域的基数,否则,两个中的较长者将被截断以匹配另一个。

So you could either take just the first and last value of the colorbrewer array, or give more values for the input domain that correspond to the respective output. 因此,您可以只获取colorbrewer数组的第一个和最后一个值,或者为输入域提供更多与相应输出相对应的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM