Gradient color in a treemap for D3

2019-01-25 00:35发布

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 http://bost.ocks.org/mike/treemap/ 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()

and

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

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?

1条回答
爷、活的狠高调
2楼-- · 2019-01-25 00:49

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; });
查看更多
登录 后发表回答