forked from thinkh/d3tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
miserables.html
104 lines (84 loc) · 2.63 KB
/
miserables.html
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
<!DOCTYPE html>
<html>
<head>
<title>Miserables</title>
<meta charset="utf-8">
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="../web_modules/d3/d3.js"></script>
<style type="text/css">
body {
width: 800px;
margin: 25px auto;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
circle {
stroke: #fff;
stroke-width: 1;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
</style>
</head>
<body>
<h1>Force Layout</h1>
<script type="text/javascript">
// Original demo from Mike Bostock: http://bl.ocks.org/mbostock/ad70335eeef6d167bc36fd3c04378048
const margin = {
top: 40,
bottom: 10,
left: 20,
right: 20
};
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;
// Creates sources <svg> element and inner g (for margins)
const svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
/////////////////////////
// compare https://github.com/d3/d3-force
const simulation = d3.forceSimulation()
.force('link', d3.forceLink().id((d) => d.id))
.force('charge', d3.forceManyBody())
.force('center', d3.forceCenter(width / 2, height / 2));
const color = d3.scaleOrdinal(d3.schemeCategory10);
d3.json('miserables.json').then((data) => {
// 1. Create Links & Nodes
// 1.1 Links data join
const link = svg.selectAll('.link').data(data.links).join(
(enter) => enter.append('line').attr('class', 'link')
);
// 1.2 Nodes data join
const node = svg.selectAll('.node').data(data.nodes).join(
(enter) => {
const node_enter = enter.append('circle')
.attr('class', 'node')
.attr('r', 10);
node_enter.append('title').text((d) => d.id);
return node_enter;
}
);
// 2. Update: Style new and existing the nodes
node.style('fill', (d) => color(d.group));
// 3. Apply force
simulation
.nodes(data.nodes)
.force('link').links(data.links);
simulation.on('tick', (e) => {
link
.attr('x1', (d) => d.source.x)
.attr('y1', (d) => d.source.y)
.attr('x2', (d) => d.target.x)
.attr('y2', (d) => d.target.y);
node
.attr('cx', (d) => d.x)
.attr('cy', (d) => d.y);
});
});
</script>
</body>
</html>