-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd3_visualization.html
103 lines (92 loc) · 3.21 KB
/
d3_visualization.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Market Basket Association Graph</title>
<style>
.node circle {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: 0.6;
}
text {
font-family: sans-serif;
font-size: 12px;
}
</style>
</head>
<body>
<h2>Market Basket Association Graph</h2>
<svg width="960" height="600"></svg>
<!-- Load D3.js -->
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
const svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
// load the JSON data (ensure the associations.json file is in the data folder relative to this HTML file)
d3.json("data/associations.json").then(function(graph) {
// initialize force simulation
const simulation = d3.forceSimulation(graph.nodes)
.force("link", d3.forceLink(graph.links).id(d => d.id).distance(150))
.force("charge", d3.forceManyBody().strength(-300))
.force("center", d3.forceCenter(width / 2, height / 2));
// draw links (edges)
const link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.attr("stroke-width", d => Math.sqrt(d.confidence * 10));
// draw nodes
const node = svg.append("g")
.attr("class", "nodes")
.selectAll("g")
.data(graph.nodes)
.enter().append("g");
node.append("circle")
.attr("r", 10)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
// add labels to nodes
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(d => d.id);
// update positions on simulation tick
simulation.on("tick", () => {
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("transform", d => `translate(${d.x},${d.y})`);
});
// drag event functions
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
}).catch(function(error){
console.error("Error loading the JSON data: ", error);
});
</script>
</body>
</html>