D3.js绘制可交互的树状图

D3 是 Data-Driven Documents 的简称,意思是数据驱动的文档,他本质上是一个 JavaScript 函数库。D3.js 的原理 是使用HTML, SVG, CSS 来表现数据,用户将数据绑定到DOM,然后根据数据来操作文档,创建可交互的图形。

18_3_17_01.png

D3的优缺点

优点:

  1. 灵活,代码简洁,功能丰富
  2. 支持数据绑定到DOM,能直接操作DOM
  3. 布局layout丰富
  4. 配色好看,能激发创造的热情
  5. 基于SVG,缩放不会损失精度
  6. 快,基于数据的高校文档操作,性能良好
  7. 社区活跃,庞大的用户群

缺点:

  1. 上手较难,需要花一定的功夫
  2. 在大量数据面前性能不如Canvas,因为DOM操作会触发浏览器重排和重绘
  3. 兼容性较差,IE9以下不支持SVG

下面我将以例子的方式来讲解如何绘制两种树状图,以及如何绑定数据到 DOM,改变数据让DOM动起来,并且添加鼠标交互的效果,以下代码基于最新版 d3.js(v4.13)

Radial Tidy Tree

18_3_17_03.png

这种树状图结构层次清晰,父与子在不同半径的位置上,这样的关系会让人一目了然,用户无需操作 DOM 就可以得到可交互式的图表,这得益于 D3 功能丰富且强大API。

HTML

svg的容器大小视情况而定,但必须设置。

1
<div id="tree" class="tree"></div>

javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
var tree, // d3 树状图对象
rootData, // 根节点
container, // g所有svg元素的容器
linkContainer, // link的容器
nodeIndex = 0; // 加id 用

draw();

function draw() {

function getStyle(oElement, sName) { // 兼容火狐和IE
return oElement.currentStyle ? oElement.currentStyle[sName] : window.getComputedStyle(oElement, null)[sName];
}

tree = d3.tree()
.size([Math.PI * 2, 600])
.separation(function(a, b) { return (a.parent === b.parent ? 1 : 2) / a.depth });

var con = d3.select("#tree"),
width = parseInt(getStyle(con._groups[0][0], "width"), 10),
height = parseInt(getStyle(con._groups[0][0], "height"), 10),
svg = con.append("svg")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("width", width)
.attr("height", height);

container = svg.append("g");
linkContainer = container.append("g");

// 注意:火狐浏览器的缩放程度是chrome的3倍
var zoom = d3.zoom()
.scaleExtent([0.4, 2])
.on("zoom", function() {
// v4: 原来的translate和scale值现在都在 event.transform 中
// d3.event.transform 等价于
// "translate(" + d3.event.transform.x + "," + d3.event.transform.y ")scale(" + d3.event.transform.k + ")"
container.attr("transform", d3.event.transform);
});
svg.call(zoom);
// 初始化g标签的位置(居中)
svg.call(zoom.transform, d3.zoomIdentity.translate(width / 2, height / 2).scale(0.9));

getData();
}

function getData() {
d3.json("data.json", function(error, data) {
if (error) throw error;

// 层次结构不变,转换成d3需要的数据结构(这时还没有坐标数据)
rootData = d3.hierarchy(data, function(d) { return d.children; });
rootData.children.forEach(collapse);

// Collapse the node and all it's children
function collapse(d) {
if(d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}

drawTree(rootData);
});
}

// 根据数据初始化结构树,以及动画逻辑
function drawTree(source) {

/*
* @method radialPoint 从12点钟方向 顺时针开始渲染
* @param {Number} x 角度
* @param {Number} y 半径
* @return {Array} 返回横坐标和纵坐标
*/
function radialPoint(x, y) {
return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)];
}

// 初始角度和半径
source.x0 = 3.141592653589793;
source.y0 = 0;

var treeData = tree(rootData); // Assigns the x and y position for the nodes.

var nodes = treeData.descendants(); // Array
var links = treeData.links(); // Array

// Normalize for fixed-depth.
nodes.forEach(function(d) {
if(d.depth === 1) {
d.y = d.depth * 180;
}else {
d.y = d.depth * 220;
}
});

var node = container.selectAll(".node")
.data(nodes, function(d) { // 必须设置id,否则会出现节点错位现象
return d.id || (d.id = ++nodeIndex);
});

// Enter
var nodeEnter = node.enter().append("g")
.attr("class", function(d) {
return "node node" + d.depth;
})
.attr("transform", function(d) {
return "translate(" + radialPoint(source.x0, source.y0) + ")";
})
.on("click", function(d) {
if(d.depth > 0) toggle(d);
});

nodeEnter.append("circle")
.attr("r", 1e-6)
.style("stroke-opacity", function(d) {
if(d.children) {
return 0.5;
}else {
return 0;
}
});

nodeEnter.append("path")
.attr("d", function(d) {
if(d.depth > 0 && d._children) {
return "M-6 -1 H-1 V-6 H1 V-1 H6 V1 H1 V6 H-1 V1 H-6 Z";
}else if(d.depth > 0 && d.children) {
return "M-6 -1 H6 V1 H-6 Z";
}
})
.style("fill-opacity", 0);

nodeEnter.append("text")
.attr("dy", function(d) {
if(d.depth === 0) return "-1.5em";
return "0.31em";
})
.attr("x", function(d) {
if(d.depth === 0) return 0;
return d.x < Math.PI ? 16 : -16;
})
.attr("text-anchor", function(d) {
if(d.depth === 0) return "middle";
return d.x < Math.PI ? "start" : "end";
})
.attr("transform", function(d) {
if(d.depth === 0) return "rotate(0)";
return "rotate(" + (d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180 / Math.PI + ")";
})
.text(function(d) {
return d.data.name;
})
.style("fill-opacity", 1e-6);

// Update
var nodeUpdate = nodeEnter.merge(node).transition()
.duration(600)
.attr("transform", function(d) {
return "translate(" + radialPoint(d.x, d.y) + ")";
});

nodeUpdate.select("circle")
.attr("r", function(d) {
if(d.depth === 0) {
return 12;
}else if(d.depth < 3) {
return 10;
}
return 8;
})
.style("stroke-opacity", function(d) {
if(d.children) {
return 0.5;
}else {
return 0;
}
});

nodeUpdate.select("path")
.attr("d", function(d) {
if(d.depth > 0 && d._children) {
return "M-6 -1 H-1 V-6 H1 V-1 H6 V1 H1 V6 H-1 V1 H-6 Z";
}else if(d.depth > 0 && d.children) {
return "M-6 -1 H6 V1 H-6 Z";
}
})
.style("fill-opacity", 1);

nodeUpdate.select("text")
.attr("x", function(d) {
if(d.depth === 0) return 0;
return d.x < Math.PI ? 16 : -16;
})
.attr("text-anchor", function(d) {
if(d.depth === 0) return "middle";
return d.x < Math.PI ? "start" : "end";
})
.attr("transform", function(d) {
if(d.depth === 0) return "rotate(0)";
return "rotate(" + (d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180 / Math.PI + ")";
})
.style("fill-opacity", 1);

// Exit
var nodeExit = node.exit().transition()
.duration(600)
.attr("transform", function(d) {
return "translate(" + radialPoint(source.x, source.y) + ")";
})
.remove();

nodeExit.select("circle")
.attr("r", 1e-6);

nodeExit.select("path")
.style("fill-opacity", 0);

nodeExit.select("text")
.style("fill-opacity", 1e-6);

var link = linkContainer.selectAll(".link")
.data(links, function(d) { // 此行配置需放在node配置之后
return d.id || (d.id = "link" + d.source.id + d.target.id);
});

var linkRadial = d3.linkRadial();
var linkEnter = link.enter().append("path")
.attr("class", "link")
.attr("d", linkRadial
.angle(function(d) {
return source.x0;
})
.radius(function(d) {
return source.y0;
})
);

linkEnter.merge(link).transition()
.duration(600)
.attr("d", linkRadial
.angle(function(d) {
return d.x;
})
.radius(function(d) {
return d.y;
})
);

link.exit().transition()
.duration(600)
.attr("d", linkRadial
.angle(function(d) {
return source.x;
})
.radius(function(d) {
return source.y;
})
)
.remove();

// Store the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});

}

function toggle(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
drawTree(d);
}

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
.tree{
width: 100%;
height: 100%;
}
.node {
cursor: pointer;
}
.node circle {
fill: #888;
}
.node text {
fill: #666;
font-size: 14px;
}
.node path {
fill: #fff;
stroke: #fff;
stroke-width: 0.2px;
}

.node0 circle {
fill: #aaceff;
stroke-opacity: 0.5;
stroke: #aaceff;
stroke-width: 8px;
}
.node1 circle {
fill: #fd9bb4;
stroke: #fd9bb4;
stroke-width: 6px;
}
.node2 circle {
fill: #af9ffc;
stroke: #af9ffc;
stroke-width: 6px;
}
.node3 circle {
fill: #9be4b7;
}
/*.node.node-child circle {
stroke-opacity: 0.5;
transform: scale(1.2);
}*/

.node:hover text {
fill: #333;
font-weight: bold;
font-size: 14px;
}
.node:hover circle {
transform: scale(1.2);
}
.node:not(.node3) text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.node0 text{
font-size: 16px!important;
}
.link {
fill: none;
stroke: #c6c6c6;
stroke-opacity: 0.4;
stroke-width: 1px;
}

data.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
{
"name": "flare",
"children": [{
"name": "analytics",
"children": [{
"name": "cluster",
"children": [{
"name": "AgglomerativeCluster",
"size": 3938
}, {
"name": "CommunityStructure",
"size": 3812
}, {
"name": "HierarchicalCluster",
"size": 6714
}, {
"name": "MergeEdge",
"size": 743
}]
}, {
"name": "graph",
"children": [{
"name": "BetweennessCentrality",
"size": 3534
}, {
"name": "LinkDistance",
"size": 5731
}, {
"name": "MaxFlowMinCut",
"size": 7840
}, {
"name": "ShortestPaths",
"size": 5914
}, {
"name": "SpanningTree",
"size": 3416
}]
}, {
"name": "optimization",
"children": [{
"name": "AspectRatioBanker",
"size": 7074
}]
}]
}, {
"name": "animate",
"children": [{
"name": "Easing",
"size": 17010
}, {
"name": "FunctionSequence",
"size": 5842
}, {
"name": "interpolate",
"children": [{
"name": "ArrayInterpolator",
"size": 1983
}, {
"name": "ColorInterpolator",
"size": 2047
}, {
"name": "DateInterpolator",
"size": 1375
}, {
"name": "Interpolator",
"size": 8746
}, {
"name": "MatrixInterpolator",
"size": 2202
}, {
"name": "NumberInterpolator",
"size": 1382
}, {
"name": "ObjectInterpolator",
"size": 1629
}, {
"name": "PointInterpolator",
"size": 1675
}, {
"name": "RectangleInterpolator",
"size": 2042
}]
}, {
"name": "ISchedulable",
"size": 1041
}, {
"name": "Parallel",
"size": 5176
}, {
"name": "Pause",
"size": 449
}, {
"name": "Scheduler",
"size": 5593
}, {
"name": "Sequence",
"size": 5534
}, {
"name": "Transition",
"size": 9201
}, {
"name": "Transitioner",
"size": 19975
}, {
"name": "TransitionEvent",
"size": 1116
}, {
"name": "Tween",
"size": 6006
}]
}, {
"name": "data",
"children": [{
"name": "converters",
"children": [{
"name": "Converters",
"size": 721
}, {
"name": "DelimitedTextConverter",
"size": 4294
}, {
"name": "GraphMLConverter",
"size": 9800
}, {
"name": "IDataConverter",
"size": 1314
}, {
"name": "JSONConverter",
"size": 2220
}]
}, {
"name": "DataField",
"size": 1759
}, {
"name": "DataSchema",
"size": 2165
}, {
"name": "DataSet",
"size": 586
}, {
"name": "DataSource",
"size": 3331
}, {
"name": "DataTable",
"size": 772
}, {
"name": "DataUtil",
"size": 3322
}]
}, {
"name": "display",
"children": [{
"name": "DirtySprite",
"size": 8833
}, {
"name": "LineSprite",
"size": 1732
}, {
"name": "RectSprite",
"size": 3623
}, {
"name": "TextSprite",
"size": 10066
}]
}, {
"name": "flex",
"children": [{
"name": "FlareVis",
"size": 4116
}]
}, {
"name": "physics",
"children": [{
"name": "DragForce",
"size": 1082
}, {
"name": "GravityForce",
"size": 1336
}, {
"name": "IForce",
"size": 319
}, {
"name": "NBodyForce",
"size": 10498
}, {
"name": "Particle",
"size": 2822
}, {
"name": "Simulation",
"size": 9983
}, {
"name": "Spring",
"size": 2213
}, {
"name": "SpringForce",
"size": 1681
}]
}, {
"name": "query",
"children": [{
"name": "AggregateExpression",
"size": 1616
}, {
"name": "And",
"size": 1027
}, {
"name": "Arithmetic",
"size": 3891
}, {
"name": "Average",
"size": 891
}, {
"name": "BinaryExpression",
"size": 2893
}, {
"name": "Comparison",
"size": 5103
}, {
"name": "CompositeExpression",
"size": 3677
}, {
"name": "Count",
"size": 781
}, {
"name": "DateUtil",
"size": 4141
}, {
"name": "Distinct",
"size": 933
}, {
"name": "Expression",
"size": 5130
}, {
"name": "ExpressionIterator",
"size": 3617
}, {
"name": "Fn",
"size": 3240
}, {
"name": "If",
"size": 2732
}, {
"name": "IsA",
"size": 2039
}, {
"name": "Literal",
"size": 1214
}, {
"name": "Match",
"size": 3748
}, {
"name": "Maximum",
"size": 843
}, {
"name": "methods",
"children": [{
"name": "add",
"size": 593
}, {
"name": "and",
"size": 330
}, {
"name": "average",
"size": 287
}, {
"name": "count",
"size": 277
}, {
"name": "distinct",
"size": 292
}, {
"name": "div",
"size": 595
}, {
"name": "eq",
"size": 594
}, {
"name": "fn",
"size": 460
}, {
"name": "gt",
"size": 603
}, {
"name": "gte",
"size": 625
}, {
"name": "iff",
"size": 748
}, {
"name": "isa",
"size": 461
}, {
"name": "lt",
"size": 597
}, {
"name": "lte",
"size": 619
}, {
"name": "max",
"size": 283
}, {
"name": "min",
"size": 283
}, {
"name": "mod",
"size": 591
}, {
"name": "mul",
"size": 603
}, {
"name": "neq",
"size": 599
}, {
"name": "not",
"size": 386
}, {
"name": "or",
"size": 323
}, {
"name": "orderby",
"size": 307
}, {
"name": "range",
"size": 772
}, {
"name": "select",
"size": 296
}, {
"name": "stddev",
"size": 363
}, {
"name": "sub",
"size": 600
}, {
"name": "sum",
"size": 280
}, {
"name": "update",
"size": 307
}, {
"name": "variance",
"size": 335
}, {
"name": "where",
"size": 299
}, {
"name": "xor",
"size": 354
}, {
"name": "_",
"size": 264
}]
}, {
"name": "Minimum",
"size": 843
}, {
"name": "Not",
"size": 1554
}, {
"name": "Or",
"size": 970
}, {
"name": "Query",
"size": 13896
}, {
"name": "Range",
"size": 1594
}, {
"name": "StringUtil",
"size": 4130
}, {
"name": "Sum",
"size": 791
}, {
"name": "Variable",
"size": 1124
}, {
"name": "Variance",
"size": 1876
}, {
"name": "Xor",
"size": 1101
}]
}, {
"name": "scale",
"children": [{
"name": "IScaleMap",
"size": 2105
}, {
"name": "LinearScale",
"size": 1316
}, {
"name": "LogScale",
"size": 3151
}, {
"name": "OrdinalScale",
"size": 3770
}, {
"name": "QuantileScale",
"size": 2435
}, {
"name": "QuantitativeScale",
"size": 4839
}, {
"name": "RootScale",
"size": 1756
}, {
"name": "Scale",
"size": 4268
}, {
"name": "ScaleType",
"size": 1821
}, {
"name": "TimeScale",
"size": 5833
}]
}, {
"name": "util",
"children": [{
"name": "Arrays",
"size": 8258
}, {
"name": "Colors",
"size": 10001
}, {
"name": "Dates",
"size": 8217
}, {
"name": "Displays",
"size": 12555
}, {
"name": "Filter",
"size": 2324
}, {
"name": "Geometry",
"size": 10993
}, {
"name": "heap",
"children": [{
"name": "FibonacciHeap",
"size": 9354
}, {
"name": "HeapNode",
"size": 1233
}]
}, {
"name": "IEvaluable",
"size": 335
}, {
"name": "IPredicate",
"size": 383
}, {
"name": "IValueProxy",
"size": 874
}, {
"name": "math",
"children": [{
"name": "DenseMatrix",
"size": 3165
}, {
"name": "IMatrix",
"size": 2815
}, {
"name": "SparseMatrix",
"size": 3366
}]
}, {
"name": "Maths",
"size": 17705
}, {
"name": "Orientation",
"size": 1486
}, {
"name": "palette",
"children": [{
"name": "ColorPalette",
"size": 6367
}, {
"name": "Palette",
"size": 1229
}, {
"name": "ShapePalette",
"size": 2059
}, {
"name": "SizePalette",
"size": 2291
}]
}, {
"name": "Property",
"size": 5559
}, {
"name": "Shapes",
"size": 19118
}, {
"name": "Sort",
"size": 6887
}, {
"name": "Stats",
"size": 6557
}, {
"name": "Strings",
"size": 22026
}]
}, {
"name": "vis",
"children": [{
"name": "axis",
"children": [{
"name": "Axes",
"size": 1302
}, {
"name": "Axis",
"size": 24593
}, {
"name": "AxisGridLine",
"size": 652
}, {
"name": "AxisLabel",
"size": 636
}, {
"name": "CartesianAxes",
"size": 6703
}]
}, {
"name": "controls",
"children": [{
"name": "AnchorControl",
"size": 2138
}, {
"name": "ClickControl",
"size": 3824
}, {
"name": "Control",
"size": 1353
}, {
"name": "ControlList",
"size": 4665
}, {
"name": "DragControl",
"size": 2649
}, {
"name": "ExpandControl",
"size": 2832
}, {
"name": "HoverControl",
"size": 4896
}, {
"name": "IControl",
"size": 763
}, {
"name": "PanZoomControl",
"size": 5222
}, {
"name": "SelectionControl",
"size": 7862
}, {
"name": "TooltipControl",
"size": 8435
}]
}, {
"name": "data",
"children": [{
"name": "Data",
"size": 20544
}, {
"name": "DataList",
"size": 19788
}, {
"name": "DataSprite",
"size": 10349
}, {
"name": "EdgeSprite",
"size": 3301
}, {
"name": "NodeSprite",
"size": 19382
}, {
"name": "render",
"children": [{
"name": "ArrowType",
"size": 698
}, {
"name": "EdgeRenderer",
"size": 5569
}, {
"name": "IRenderer",
"size": 353
}, {
"name": "ShapeRenderer",
"size": 2247
}]
}, {
"name": "ScaleBinding",
"size": 11275
}, {
"name": "Tree",
"size": 7147
}, {
"name": "TreeBuilder",
"size": 9930
}]
}, {
"name": "events",
"children": [{
"name": "DataEvent",
"size": 2313
}, {
"name": "SelectionEvent",
"size": 1880
}, {
"name": "TooltipEvent",
"size": 1701
}, {
"name": "VisualizationEvent",
"size": 1117
}]
}, {
"name": "legend",
"children": [{
"name": "Legend",
"size": 20859
}, {
"name": "LegendItem",
"size": 4614
}, {
"name": "LegendRange",
"size": 10530
}]
}, {
"name": "operator",
"children": [{
"name": "distortion",
"children": [{
"name": "BifocalDistortion",
"size": 4461
}, {
"name": "Distortion",
"size": 6314
}, {
"name": "FisheyeDistortion",
"size": 3444
}]
}, {
"name": "encoder",
"children": [{
"name": "ColorEncoder",
"size": 3179
}, {
"name": "Encoder",
"size": 4060
}, {
"name": "PropertyEncoder",
"size": 4138
}, {
"name": "ShapeEncoder",
"size": 1690
}, {
"name": "SizeEncoder",
"size": 1830
}]
}, {
"name": "filter",
"children": [{
"name": "FisheyeTreeFilter",
"size": 5219
}, {
"name": "GraphDistanceFilter",
"size": 3165
}, {
"name": "VisibilityFilter",
"size": 3509
}]
}, {
"name": "IOperator",
"size": 1286
}, {
"name": "label",
"children": [{
"name": "Labeler",
"size": 9956
}, {
"name": "RadialLabeler",
"size": 3899
}, {
"name": "StackedAreaLabeler",
"size": 3202
}]
}, {
"name": "layout",
"children": [{
"name": "AxisLayout",
"size": 6725
}, {
"name": "BundledEdgeRouter",
"size": 3727
}, {
"name": "CircleLayout",
"size": 9317
}, {
"name": "CirclePackingLayout",
"size": 12003
}, {
"name": "DendrogramLayout",
"size": 4853
}, {
"name": "ForceDirectedLayout",
"size": 8411
}, {
"name": "IcicleTreeLayout",
"size": 4864
}, {
"name": "IndentedTreeLayout",
"size": 3174
}, {
"name": "Layout",
"size": 7881
}, {
"name": "NodeLinkTreeLayout",
"size": 12870
}, {
"name": "PieLayout",
"size": 2728
}, {
"name": "RadialTreeLayout",
"size": 12348
}, {
"name": "RandomLayout",
"size": 870
}, {
"name": "StackedAreaLayout",
"size": 9121
}, {
"name": "TreeMapLayout",
"size": 9191
}]
}, {
"name": "Operator",
"size": 2490
}, {
"name": "OperatorList",
"size": 5248
}, {
"name": "OperatorSequence",
"size": 4190
}, {
"name": "OperatorSwitch",
"size": 2581
}, {
"name": "SortOperator",
"size": 2023
}]
}, {
"name": "Visualization",
"size": 16540
}]
}]
}

Radial Dendrogram

18_3_17_02.png

这种布局看起来不太紧凑,但有时候却很有用,所有叶子节点都在统一水平,可以利用鼠标交互高亮来突出内部节点到根节点的深度。

更多cluster布局

HTML

HTML代码同上

javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var tree, // d3 树型图对象
rootData, // 根节点
container, // g所有svg元素的容器
linkContainer, // link的容器

draw();

function draw() {

function getStyle(oElement, sName) { // 兼容火狐和IE
return oElement.currentStyle ? oElement.currentStyle[sName] : window.getComputedStyle(oElement, null)[sName];
}

tree = d3.cluster()
.size([360, 600])
.separation(function(a, b) { return (a.parent === b.parent ? 1 : 2) / a.depth });

var con = d3.select("#tree"),
width = parseInt(getStyle(con._groups[0][0], "width"), 10),
height = parseInt(getStyle(con._groups[0][0], "height"), 10),
svg = con.append("svg")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("width", width)
.attr("height", height);

container = svg.append("g");
linkContainer = container.append("g");

// 注意:火狐浏览器的缩放程度是chrome的3倍
var zoom = d3.zoom()
.scaleExtent([0.4, 2])
.on("zoom", function() {
container.attr("transform", d3.event.transform); //v4: 原来的translate和scale值现在都在 event.transform 中
});
svg.call(zoom);
// 初始化g标签的位置(居中)
svg.call(zoom.transform, d3.zoomIdentity.translate(width / 2, height / 2).scale(0.9));

getData();
}

function getData() {
d3.json("data.json", function(error, data) {
if (error) throw error;

rootData = d3.hierarchy(data, function(d) { return d.children; }); // 层次结构不变,转换成d3需要的数据结构(这时还没有坐标数据)

drawTree(rootData);
});
}

function drawTree(source) {
var treeData = tree(rootData);

var nodes = treeData.descendants();
var links = treeData.links();
// console.log(nodes);

var linkRadial = d3.linkRadial();

var link = linkContainer.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", linkRadial
.angle(function(d) {
return d.x * Math.PI / 180;
})
.radius(function(d) {
return d.y;
})
);

var node = container.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", function(d) {
return "node" + (d.children ? " node-internal" : " node-leaf");
})
.attr("transform", function(d) {
return "translate(" + radialPoint(d.x, d.y) + ")";
});

node.append("circle")
.attr("r", function(d) {
if(d.children) {
return 8;
}else {
return 6;
}
});

node.append("text")
.attr("dy", "0.31em")
.attr("x", function(d) {
return (d.x < 180) === !d.children ? 12 : -12;
})
.style("text-anchor", function(d) {
return (d.x < 180) === !d.children ? "start" : "end";
})
.attr("transform", function(d) {
return "rotate(" + (d.x < 180 ? d.x - 90 : d.x + 90) + ")";
})
.text(function(d) {
return d.data.name;
});

function radialPoint(x, y) {
var angle = (x - 90) / 180 * Math.PI, radius = y;
return [radius * Math.cos(angle), radius * Math.sin(angle)];
}
}

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
.tree{
width: 100%;
height: 100%;
}
.node {
cursor: pointer;
}

.node circle {
fill: #888;
/*stroke-opacity: 0;*/
}
.node text {
fill: #666;
font-size: 14px;
}
.node:hover text {
fill: #333;
font-weight: bold;
}
.node:hover circle {
transform: scale(1.2);
}
.node-internal circle{
fill: #fd9bb4;
}
.node-leaf circle{
fill: #af9ffc;
}
.node:not(.node-leaf) text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #c6c6c6;
stroke-opacity: 0.4;
stroke-width: 1px;
}

提示

D3 的代码可以完美地植入到 React 中,在componentDidMount中操作就行,无需setState,D3 会自动更新 DOM,你只需处理相关数据的逻辑就可以了。
D3 的布局还有好几种,以后还会具体讲到,敬请关注。

✧(≖‿≖)✧ 谢谢您的支持 (●'◡'●)ノ♥
0%