这一节学习树状图的制作。树状图的制作和集群图完全相同,经过这两种 layout 转换后的数据也很相似。
本人的个人博客为: www.ourd3js.com
csdn博客为: blog.csdn.net/lzhlzz
转载请注明出处,谢谢。
{ "name":"中国", "children": [ { "name":"浙江" , "children": [ {"name":"杭州" }, {"name":"宁波" }, {"name":"温州" }, {"name":"绍兴" } ] }, { "name":"广西" , "children": [ { "name":"桂林", "children": [ {"name":"秀峰区"}, {"name":"叠彩区"}, {"name":"象山区"}, {"name":"七星区"} ] }, {"name":"南宁"}, {"name":"柳州"}, {"name":"防城港"} ] }, { "name":"黑龙江", "children": [ {"name":"哈尔滨"}, {"name":"齐齐哈尔"}, {"name":"牡丹江"}, {"name":"大庆"} ] }, { "name":"新疆" , "children": [ {"name":"乌鲁木齐"}, {"name":"克拉玛依"}, {"name":"吐鲁番"}, {"name":"哈密"} ] } ] }
集群图的结果为:
树状图的结果为:
知道有什么分别了吗?下面是树状图的代码:
<html> <head> <meta charset="utf-8"> <title>Tree</title> </head> <style> .node circle { fill: #fff; stroke: steelblue; stroke-width: 1.5px; } .node { font: 12px sans-serif; } .link { fill: none; stroke: #ccc; stroke-width: 1.5px; } </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var width = 500, height = 500; var tree = d3.layout.tree() .size([width, height-200]) .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; }); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(40,0)"); d3.json("city_tree.json", function(error, root) { var nodes = tree.nodes(root); var links = tree.links(nodes); console.log(nodes); console.log(links); var link = svg.selectAll(".link") .data(links) .enter() .append("path") .attr("class", "link") .attr("d", diagonal); var node = svg.selectAll(".node") .data(nodes) .enter() .append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) node.append("circle") .attr("r", 4.5); node.append("text") .attr("dx", function(d) { return d.children ? -8 : 8; }) .attr("dy", 3) .style("text-anchor", function(d) { return d.children ? "end" : "start"; }) .text(function(d) { return d.name; }); }); </script> </body> </html>这段代码和9.4节的代码完全相同。除了 33行,定义的 layout 由 cluster 变为 tree 之外,其他的都是一样的。
【 D3.js 入门系列 --- 9.5 】 树状图的制作,布布扣,bubuko.com
原文:http://blog.csdn.net/lzhlzz/article/details/38561737