gpt4 book ai didi

javascript - 使用 D3.JS 为 Nest 树状图着色

转载 作者:行者123 更新时间:2023-11-30 20:47:17 24 4
gpt4 key购买 nike

我正致力于从 csv 文件创建树状图。 csv 文件中的数据是分层的,看起来像我从另一个 Stack Overflow 问题中窃取的这个例子

parent,child,value
Homer Simpson,Bart,20
Homer Simpson,Lisa,14
Homer Simpson,Maggie,6
Peter Griffin,Chris,19
Peter Griffin,Meg,12
Peter Griffin,Stewie,9

我正在使用 d3.nest(),因为我不想像 so 那样重新格式化我的 CSV .我的大部分文件都从 Mike Bostock 的 Nest Treemap 中被盗了 here ,但我无法弄清楚如何以不同的方式为 parent 着色,而且我对 Javascript 和 D3 都很陌生。这是我正在使用的脚本

<script>

var format = d3.format(",d"),
color = d3.scaleOrdinal(d3.schemeCategory10);

var nest = d3.nest()
.key(function(d) {return d.parent;})
.key(function(d) {return d.child;})
.rollup(function(d) {return d3.sum(d, function(d) {return d.value;}); });

var treemap = d3.treemap()
.size([960, 960])
.round(true)
.padding(1);

d3.csv("d3.csv", function(error, data) {
if (error) throw error;

data.forEach(function(d) {
if (d.parent == "null") { d.parent = null};
});

var root = d3.hierarchy({values: nest.entries(data)}, function(d) { return d.values; })
.sum(function(d) { return d.value; })
.sort(function(a, b) { return b.value - a.value; });

treemap(root);

var node = d3.select("body")
.selectAll(".node")
.data(root.leaves())
.enter().append("div")
.attr("class", "node")
.style("left", function(d) { return d.x0 + "px"; })
.style("top", function(d) { return d.y0 + "px"; })
.style("width", function(d) { return d.x1 - d.x0 + "px"; })
.style("height", function(d) { return d.y1 - d.y0 + "px"; })
.style("background", function(d) { while (d.depth > 1) d = d.parent; return color(d.id); })

node.append("div")
.attr("class", "node-label")
.text(function(d) { return d.parent.data.key + "\n" + d.data.key; });

node.append("div")
.attr("class", "node-value")
.text(function(d) { return format(d.value); });
});

</script>

Here's what happens

如何为不同的 block 着色?我一直坚持实现背景样式,不明白为什么所有的 parent 似乎都有相同的颜色。我相信让 parent 正确也会帮助我实现缩放。

最佳答案

因为没有属性 d.id(用于设置填充),这将返回 undefined,并且所有元素的颜色都将与序号比例相同。

要在此处获取父级的标识符,我们需要查看 d.data 属性,其中包含另一个对象:

{ 
key: "Homer Simpson",
values: [children]
}

如果你想根据 parent 给 child 上色,使用d.data.key:

.style("background", function(d) { while (d.depth > 1) d = d.parent; return color(d.data.key); })

关于javascript - 使用 D3.JS 为 Nest 树状图着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com