我想要复制Mike Bostock的可折叠树形图(http://bl.ocks.org/mbostock/4339083)。
我已使用nest
中的d3.js
功能加载了CSV。现在,数据看起来像这样:
[
{
"key": "Bayer HealthCare",
"values": [
{
"key": "Animal Health",
"values": [
{
"key": "Companion Animal",
"values": [
{
"brand": "Drontal",
"product": "Companion Animal",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
},
{
"brand": "Profender",
"product": "Companion Animal",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
},
{
"brand": "Rompun",
"product": "Companion Animal",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
}
]
},
{
"key": "Companion Animal - Food Animal Product",
"values": [
{
"brand": "Baytril",
"product": "Companion Animal - Food Animal Product",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
}
]
},
{
"key": "Companion animals",
"values": [
{
"brand": "Advantage",
"product": "Companion animals",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
},
{
"brand": "Advantix",
"product": "Companion animals",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
},
{
"brand": "Advocate",
"product": "Companion animals",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
}
]
},
{
"key": "Food Animal Product",
"values": [
{
"brand": "Baycox",
"product": "Food Animal Product",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
},
{
"brand": "Catosal",
"product": "Food Animal Product",
"subgroup": "Bayer HealthCare",
"division": "Animal Health"
}
]
}
]
}
.....
(完整数据以及我目前所做的工作可在此处获取:http://jsfiddle.net/L3phF/9/)
不幸的是我不知道如何将数据转换为像这样https://gist.github.com/mbostock/1093025的“FLARE JSON”格式。如果我是对的,我必须将“key”重命名为“name”,将“values”重命名为“children”,并且我必须在最低级别的每个对象前插入“”name:“”。
我感谢任何帮助!
答案 0 :(得分:3)
这将重命名" key" to" name"和"价值观"儿童":
var renameKeys=function(obj){
/*Recursively renames "key" keys to "name" and
renames "values" keys to "children" */
obj.name=obj.key;
delete obj['key'];
if(obj.values){
obj.children=obj.values;
delete obj.values;
obj.children.forEach(renameKeys);
}
return obj;
};
你还需要给JSON一个" root"节点,以便使用您链接到的可折叠树可视化。这应该这样做:
var nest = d3.nest()
.key(function(d) { return d.subgroup; })
.key(function(d) { return d.division; })
.key(function(d) { return d.product; })
.entries(parsed);
/*The visualization requires there to be a root node*/
var flareData={key:'root',values:[]};
flareData.values=nest;
renameKeys(flareData);
这是一个获取所需JSON的JSFiddle:http://jsfiddle.net/X2fxC/3/
这是一个带有结果可视化的JSFiddle: http://jsfiddle.net/X2fxC/5/
使用展开式树形象显示时,您的数据如下所示: