Gradient color in a treemap for D3


First of all this is different from the previous question asked in the posts, for what i am trying to achieve is a gradient for the entire treemap in d3, like what we have in google treemaps.

I am trying to implement and working on the same, but in d3 i was trying to have a color gradient in it.

Currently I am doing this by

color = d3.scale.category20c()


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

on my svg element. But i want to have a gradiant color more like a heatmap, so as to make larger boxes in treemap more green and smaller boxes less green. is there a way in d3/css to specify that?

Problem courtesy of: neoeahit


It sounds like you want a color scale applied to each box in the treemap. This is pretty simple:

var colorScale = d3.scale.linear()
    .range(['lightgreen', 'darkgreen']) // or use hex values
    .domain([minValue, maxValue]);

Then apply with

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

The hard part here is determining the domain - depending on how your data is structured, you might need to walk the tree to collect it. In the Bostock example, you can get the extent of the data after you've joined it to the elements like this:

d3.extent(d3.selectAll('rect.child').data(), function(d) { return d.value; });
Solution courtesy of: nrabinowitz


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.