d3生成的树状图

 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>

 

posted @ 2019-01-23 15:49  前端极客  阅读(6136)  评论(0编辑  收藏  举报