d3分位数比例力第一分位数

时间:2016-02-17 13:08:54

标签: javascript d3.js range scale quantile

我正在构建一个热图,其颜色渐变从绿色到红色。我希望值为0的单元格为绿色,值大于或等于1以取其他颜色。 我正在用这种方式建立规模:

var colors = [
  '#27C24C',
  '#7DB22E',
  '#D4A10F',
  '#F97C20',
  '#F35F40',
  '#FF0000'
];

var colorScale = d3.scale.quantile()
  .domain([0, d3.max(data, function (d) { return d.value; })])
  .range(colors);

但这会给我带来以下分位数:

[239.16666666666677, 478.3333333333332, 717.5, 956.6666666666664, 1195.8333333333335]

因此,我有以下热图: Wrong heat map
但我希望尖头的细胞是绿色的第二个阴影,因为它的值严格大于0

2 个答案:

答案 0 :(得分:0)

在这种情况下,您不能仅使用分位数刻度。编写自定义比例函数以分别处理零值。

var colors = [
  // '#27C24C', this value must not be included in the internal range
  '#7DB22E',
  '#D4A10F',
  '#F97C20',
  '#F35F40',
  '#FF0000'
];

var colorScaleInternal = d3.scale.quantile()
  .domain([0, d3.max(data, function (d) { return d.value; })])
  .range(colors);

var colorScale = function(value) {
  return !!value ? colorScaleInternal(value) : '#27C24C';
};

答案 1 :(得分:0)

虽然我在D3中找不到对此功能的支持,但我能够通过改变发送到d3的范围数组来解决这个问题。我的想法是用D3检查四分位数是否重复,如果是,请为所有四分之一保持相同的颜色:

var scale = d3.scale.quantile().domain(domain).range(range);

var quantiles = scale.quantiles();
quantiles.unshift(d3.min(domain));

// Now that you have the quantiles, you can see if some of them are holding the same value, 
// and it that case set the minimum value to all of them.
var modifiedRange = [range[0]];
for (var i = 1; i < range.length; i++) {
    if (quantiles[i] === quantiles[i - 1]) {
        modifiedRange.push(modifiedRange[i - 1]);
    } else {
        modifiedRange.push(range[i]);
    }
}

// set the new scale
scale.range(modifiedRange);