[英]d3 v5 interpolate color on treemap
我正在基于以下示例在d3 v5中构建树形图: https : //www.d3indepth.com/layouts/
我可以使用score
数据点作为最低级别的孩子的色阶,但是我希望上方方框的父母平均有下面的孩子。
我的数据样本在这里:
{
"name": "Unit",
"children": [
{
"name": "SBU",
"children": [
{
"name": "App",
"value": 3000,
"score": 0.5
},
{
"name": "App",
"value": 3500,
"score": 0.1
},
{
"name": "App",
"value": 2000,
"score": 0.9
}
]
}
代码如下:
d3.json("health.json").then(function(data) {
console.log(data)
var treemapLayout = d3.treemap()
.size([1700, 1500])
.paddingOuter(16);
var rootNode = d3.hierarchy(data)
// Determine the size and placement of the boxes
rootNode
.sum(function(d) { return d.value; })
.sort(function(a,b) { return b.value - a.value; });
treemapLayout(rootNode);
var nodes = d3.select('svg g')
.selectAll('g')
.data(rootNode.descendants())
.enter()
.append('g')
.attr('transform', function(d) {return 'translate(' + [d.x0, d.y0] + ')'})
nodes
.append('rect')
.attr('width', function(d) { return d.x1 - d.x0; })
.attr('height', function(d) { return d.y1 - d.y0; })
.attr('style', function(d) {
return ('fill:' + d3.interpolateRdYlGn(d.data.health))
})
nodes
.append('text')
.attr('dx', 4)
.attr('dy', 14)
.text(function(d) {
return d.data.name;
})
});
一种方法是对数据进行预处理,以包括父节点的平均子得分以及每个节点的颜色:
计算每个父节点的平均子得分,并将结果添加到您的数据结构中。
{ "name": "SBU", "avgScore": 0.5, "children: [
使用顺序刻度将这些平均结果映射到d3.interpolateRdYlGn等特定颜色,并将结果添加到数据中:
const colorScale = d3.scaleSequential(d3.interpolateRdYlGn) .domain([0, 1]); // depending on your data const nodeColor = colorScale(data.parent.avgScore); { "name": "SBU", "avgScore": 0.5, "nodeColor": nodeColor }
然后,您可以为根节点和子节点的数据分配特定的颜色:
const childNodeColor = rgb(100, 200, 100); { // Child node ..., nodeColor: childNodeColor }
然后,只需使用以下命令为树中的每个节点渲染颜色:
... .attr('style', function(d) { return colorScale(d.nodeColor); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.