如何使用 d3.domain/range 来拥有自定义域

How to use d3.domain/range to have a custom domain

我目前正在使用

的整个想法
var myQuantizeFunction = d3.scale.quantize()
                                 .domain(minMaxFromData) // the minmax using d3.extent
                                 .range(['bla-1', 'bla-2', 'bla-3', 'bla-4', 'bla-5']);

因此,当您想要在最小-最大范围内生成图例时,此方法可以正常工作。问题是,我有一些返回为 0 的数据。

这是上下文的示例图例:

如您所见,它是范围内的第一个或最小值是 0 - 4.7,我真正想要做的是将 0(即 none)作为它自己的图例项并具有上面的所有内容,即1 - 33 在这种情况下作为其他范围。

我希望能够指定第一个范围是 0,然后域在 > 0 的值之间平分。

是否有 d3 方法可以做到这一点?我敢肯定其他人以前一定遇到过同样的问题,我似乎找不到它,但我可能没有使用正确的搜索词。

来自文档:

quantize.domain([numbers])

If numbers is specified, sets the scale's input domain to the specified two-element array of numbers. If the array contains more than two numbers, only the first and last number are used. If the elements in the given array are not numbers, they will be coerced to numbers; this coercion happens similarly when the scale is called. Thus, a quantize scale can be used to encode any type that can be converted to numbers. If numbers is not specified, returns the scale's current input domain.

顾名思义,d3 是 'data driven',因此忽略部分数据集不是其精神的一部分。

您需要编写自己的函数来生成 [numbers] 数组。

尝试:

data = [0,0,2,1,4,6,7,8,4,3,0,0];

min = undefined;
data.forEach(function (v) {
    if (v > 0) {
        if (typeof(min) === 'undefined') {
            min = v;
        } else if (v < min) {
            min = v;
        }
    }
})

var myQuantizeFunction = d3.scale.quantize()
                                 .domain([min, d3.max(data)])
                                 .range(['bla-1', 'bla-2', 'bla-3', 'bla-4', 'bla-5']);

我改进了 以使用 d3.min() 并添加了代码来测试量化功能。我还添加了一个小函数来为输出着色。

一切都以 d3 数据驱动的方式完成

data = [0,0,2,1,4,6,7,8,4,3,0,0];
range = ['bla-1', 'bla-2', 'bla-3', 'bla-4', 'bla-5'];

//strip the first element
reducedRange = range.slice();
reducedRange.shift();

var myQuantizeFunction = 
    d3.scale.quantize()
      .domain([d3.min(data), d3.max(data)])
      .range(reducedRange);

var filterQuantize = function(d){
  if(d==0){
    return range[0];
  }else{
    return myQuantizeFunction(d);
  }
}

var colorize = d3.scale.category10();
// To test this we will put all the data in paragraphs
d3.select('body').selectAll('p').data(data)  .enter()
  .append('p')
  .text(function(d){return d+':'+filterQuantize(d);})
  .style('color',function(d){return colorize(d)});

View this code runing

希望对您有所帮助,祝您好运!

更新: 正如您在评论中指出的那样,我从量表中删除了零以将其视为特例。