Question

In the example, http://mbostock.github.com/d3/ex/bubble.html:

Enter image description here

In line 27:

.style("fill", function(d) { return fill(d.packageName); });

Where is fill() defined? I didn't find it in d3.js either. And even if the package name is not a color, some random color is being assigned. How so?

Was it helpful?

Solution

Take a look at the very top of the snippet you linked:

var r = 960,
    format = d3.format(",d"),
    fill = d3.scale.category20c();

That third line is where fill is being defined. You can find the doc for category20c here:

https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-category20

OTHER TIPS

The source code is on lines 2997- on d3.v2.js:

d3.scale.category20c = function() {
  return d3.scale.ordinal().range(d3_category20c);
};

Which is calling:

// lines 2894-2896
d3.scale.ordinal = function() {
  return d3_scale_ordinal([], {t: "range", x: []});
};

Which then calls

// lines 2903-2905
function scale(x) {
    return range[((index.get(x) || index.set(x, domain.push(x))) - 1) % range.length];
}

The parameter passed in, x is set to d3_category20c which assigns colors from the list of 20 available colors seen below:

["#3182bd", "#6baed6", "#9ecae1", 
"#c6dbef", "#e6550d", "#fd8d3c", 
"#fdae6b", "#fdd0a2", "#31a354", 
"#74c476", "#a1d99b", "#c7e9c0", 
"#756bb1", "#9e9ac8", "#bcbddc", 
"#dadaeb", "#636363", "#969696", 
"#bdbdbd", "#d9d9d9"]

Stepping through the code I see the colors assigned like this (based on the category passed in):

cluster = 0 #3182bd
graph = 1 #6baed6
optimization = 2 #9ecae1
animate = 3  #c6dbef
interpolate = 4 #e6550d
converters = 5 #fd8d3c
data = 6 #fdae6b
display = 7 #fdd0a2
flex = 8 #31a354
physics = 9  #74c476
query = 10 #a1d99b
methods = 11 #c7e9c0
scale = 12 #756bb1
util = 13 #9e9ac8
heap = 14 #bcbddc
math = 15 #dadaeb
palette = 16 #636363
axis = 17 #969696
controls = 18 #bdbdbd
render = 19 #d9d9d9
events = 0 #3182bd
legend = 1 #6baed6
etc...

Note, it's using the mod operator so it can keep assigning colors if the number of passed in categories exceeds the range of 20 colors.

Note, the colors for d3_category20c are defined in category.js, lines 48-54.

As already mentioned, this code:

var r = 960,
    format = d3.format(",d"),
    fill = d3.scale.category20c();

defines fill(). I just want to add following handy combination of documentation and reference card:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top