Anna Melzer
Anna Melzer

Reputation: 1613

D3: ordinal scale not working with array of objects

still struggeling with d3.

I tried build an ordinal scale where the domain is an array of objects. Somehow rangeBands is not working with this type of array. It works with a string or number array. Can anybody explain why?

var number_data = [1,2,3,4,5];

var string_data = ["1","2","3","4","5"]

var object_data = [{"test":"1" },{"test":"2"},{"test":"3"},{"test":"4"},{"test":"5"}]

console.log("+++ Array of Numbers +++")
var scale= d3.scale.ordinal()
                .domain(number_data)
                .rangeBands([0,100]);

number_data.forEach(function(d){
    console.log(scale(d));
});

console.log("+++ Array of Strings +++")
scale.domain(string_data);

string_data.forEach(function(d){
    console.log(scale(d));
});

console.log("+++ Array of Objects +++")
scale.domain(object_data);

object_data.forEach(function(d){
    console.log(scale(d));
});

http://jsfiddle.net/tgtrtv9e/

Upvotes: 0

Views: 706

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

You cannot use objects with ordinal scales. Internally, the mapping from input to output uses D3 maps, which coerce the keys (i.e. the input) to strings. For objects, the result is "[object Object]" for all objects. That is, all objects "look" the same to an ordinal scale.

Upvotes: 3

Related Questions