我一直试图将一个小的数据集加载到d3.js中,以用于其他d3方面。它只有两个深度,但是我在努力使D3正确加载。我尝试了以下方法,在我看来应该可行?
let hierarchy = d3
.hierarchy()
.children(d => d.foods)
.sum(d => d.total)
有问题的数据示例是:
let data = {
'SetA': {
foods: [
{ food: 'Apple', total: 1 },
{ food: 'Banana', total: 1 },
{ food: 'Orange', total: 3 }
], label: 'fruits', size: 3
},
'SetB': {
foods: [
{ food: 'Potato', total: 2 },
{ food: 'Carrot', total: 4 }
], label: 'vegetables', size: 2
}
}
答案 0 :(得分:0)
您可能想按照d3.hierarchy
的名称来命名和组织数据,请查看documentation here
返回的节点和每个后代具有以下属性:
node.data - the associated data, as specified to the constructor. node.depth - zero for the root node, and increasing by one for each descendant generation. node.height - zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes. node.parent - the parent node, or null for the root node. node.children - an array of child nodes, if any; undefined for leaf nodes. node.value - the summed value of the node and its descendants; optional, see node.sum and node.count.
因此您的数据应类似于:
let data = {
name: 'root',
children: [{
name: 'foods A',
children: [
{
name: 'fruits',
children: [
{ name: 'Apple', size: 1 },
{ name: 'Banana', size: 1 },
{ name: 'Orange', size: 3 },
],
label: 'fruits',
size: 3,
}]},
{
name: 'foods B',
children: [
{
name: 'vegetables',
children: [
{ name: 'Potato', size: 2 },
{ name: 'Carrot', size: 4 }
],
label: 'vegetables',
size: 2
}]
}]
}