1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>樹形圖(集群圖)</title> 6 <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> 7 <style> 8 svg{ 9 display: block; 10 width: 1000px; 11 height: 800px; 12 margin: 100px auto; 13 } 14 path.link{ 15 stroke: #333; 16 stroke-width: 1.5px; 17 fill:transparent; 18 } 19 .node circle{ 20 fill:#fff; 21 stroke:steelblue; 22 stroke-width: 1.5px; 23 } 24 </style> 25 </head> 26 <body> 27 <!--數據一共3級--> 28 <svg></svg> 29 </body> 30 </html> 31 <script> 32 33 var tree = d3.layout.tree() 34 .size([600, 400])//設定尺寸,即轉換后的各個節點的坐標在哪一個范圍內; 35 .separation(function (a, b) {//設置節點之間的間隔; 36 return (a.parent == b.parent ? 1 : 2) 37 }); 38 // 轉換數據 39 d3.json('tree.json',function (error,root) {//root是讀入的數據; 40 var nodes = tree.nodes(root); 41 var links = tree.links(nodes); 42 console.log(nodes)//nodes中有各個節點的子節點(children),深度(depth),名稱(name).位置(x,y)信息;其中name是json文件中的屬性 43 console.log(links)//links中有連線兩端(source,target)的節點信息; 44 // 繪制 45 // d3.svg.diagonal()是一個對角線生成器,只要輸入兩個頂點坐標,即可生成一條貝塞爾曲線 46 // 創建一個對角線生成器 47 var diagonal = d3.svg.diagonal() 48 .projection(function(d){return [d.y,d.x]})//projection()是一個點變換器,默認是【d.x,d.y】,即保持原坐標不變,如果寫成 [ d.y , d.x ] ,即是說對任意輸入的頂點,都交換 x 和 y 坐標。 49 var svg = d3.select('svg') 50 .append('g')//不加這個g的時候,中國兩個字出不來; 51 .attr("transform", "translate(140,0)"); 52 // 繪制連線方法 53 var link = svg.selectAll('.link') 54 .data(links) 55 .enter() 56 .append('path') 57 .attr('class','link') 58 .attr('d',diagonal) 59 var node = svg.selectAll('.node') 60 .data(nodes) 61 .enter() 62 .append('g') 63 .attr('class','node') 64 .attr('transform',function (d) { 65 return "translate(" + d.y + "," + d.x + ")"; 66 }) 67 node.append('circle') 68 .attr('r',4.5) 69 node.append('text') 70 .attr("dx", function(d) { return d.children ? -8 : 8; }) 71 .attr("dy", 3) 72 .style("text-anchor", function(d) { return d.children ? "end" : "start"; }) 73 .text(function(d) { return d.name; }); 74 }) 75 76 </script>