Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the type of a scale in D3?

Tags:

d3.js

If I create two scales:

a = d3.scale.ordinal()
b = d3.scale.linear()

How can I know which is ordinal and which is linear? Something like d3.scale.isOrdinal(a)

like image 825
nachocab Avatar asked May 30 '13 16:05

nachocab


2 Answers

Add your own type property when you create the scale:

var scaleType = {
    LINEAR: "LINEAR",
    POWER: "POWER",
    LOG: "LOG",
    ORDINAL: "ORDINAL"    
};

var scale_a = d3.scale.ordinal()
    .domain([1,2,3])
    .range([0,100]);
scale_a.type = scaleType.ORDINAL;

var scale_b = d3.scale.linear()
    .domain([0,100])
    .range([0,100]);
scale_b.type = scaleType.LINEAR;    
like image 80
user1618323 Avatar answered Oct 22 '22 15:10

user1618323


there is no direct way to know i.e. there is not a property of the scale functions that tells you which type of scale it is.

The best way to do it is to test for the scale interface by checking for the presence/absence of any configuration method present in one of the types and not the other.

For instance:

typeof a.rangePoints === "function"
typeof b.rangePoints === "undefined"

The ordinal scale exposes a rangePoints function while the linear scale doesn't

like image 23
LucaM Avatar answered Oct 22 '22 15:10

LucaM