d3 中的自定义比例

问题描述 投票:0回答:2

d3 中有很多缩放函数(例如:d3.scale.linear()、d3.scale.sqrt()、d3.scale.log(),...)。但对于特定情况,我需要不同的尺度函数(准确地说是“广义逻辑函数”)。有没有办法在 d3 中定义自定义比例函数?喜欢

function d3.scale.mycustom() {
       ...
}

从数学角度来看很简单,但是如何在 d3 中实现呢?

在Enche的提示下,我尝试了以下方法:

var my_custom_scale = function interpolate(t) {

    var A  = 0;
    var K  = 1;
    var B  = 10;
    var NU = 0.7;
    var Q  = 0.5;
    var C  = 1;

    return A + (K - A) / Math.pow(C + Q * Math.exp(-1 * B * (t - 0.5)), 1 / NU);

}

哪个有效:

console.log(my_custom_scale(0.0)); // 0.0021
console.log(my_custom_scale(0.1)); // 0.0084
console.log(my_custom_scale(0.2)); // 0.0324
console.log(my_custom_scale(0.3)); // 0.1098
console.log(my_custom_scale(0.4)); // 0.2934
console.log(my_custom_scale(0.5)); // 0.5603
console.log(my_custom_scale(0.6)); // 0.7857
console.log(my_custom_scale(0.7)); // 0.9107
console.log(my_custom_scale(0.8)); // 0.9655
console.log(my_custom_scale(0.9)); // 0.9871
console.log(my_custom_scale(1.0)); // 0.9952

但是我现在如何将其作为

d3.scale.my_custom_scale
提供?

d3.js
2个回答
1
投票

维基百科的这篇文章对我来说有点难以编写实际的代码,但是:

有没有办法在d3中定义自定义比例函数?

是的!请参阅此处。您可能想要/需要使用 插值器,您会经常在定量尺度页面上看到引用。


0
投票

为了扩展 enche 的答案,以下是如何使用插值器定义自定义比例:

var interpolatorFactory = function(a, b) {
    return function(t) {
        // Your custom scale function here, 
        // where you interpolate between a and b 
        // using the parameter t.
        return a * (1 - t) + b * t;
    };
};
var myScale = d3.scaleLinear().interpolate(interpolatorFactory);
// myScale is a standard d3 scale, so you can do 
// myScale.range([0, 5])
// myScale.domain([1, 3]) 
// etc
© www.soinside.com 2019 - 2024. All rights reserved.