-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathd3swarmchart.html
95 lines (85 loc) · 2.51 KB
/
d3swarmchart.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
<!-- Source code and data for the swarm plot tutorial at https://www.chartfleau.com/tutorials/d3swarm
This code introduces the concept of a D3 force simulation to lay out elements on a chart.
A video lesson walking through a more advanced project, including fluid animation of time series data,
is now available from Gumroad: https://chartfleau.gumroad.com/l/masterclass -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://d3js.org/d3.v5.min.js"></script>
<title>D3 Swarm Plot</title>
</head>
<body></body>
</html>
<script>
const width = 1920;
const height = 1080;
const margin = [50, 60, 50, 100];
let svg = d3
.select("body")
.append("svg")
.attr("height", height)
.attr("width", width);
d3.csv("data.csv").then((data) => {
let sectors = Array.from(new Set(data.map((d) => d.Sector)));
let xScale = d3
.scaleBand()
.domain(sectors)
.range([margin[3], width - margin[1]]);
let yScale = d3
.scaleLinear()
.domain(d3.extent(data.map((d) => +d["Return"])))
.range([height - margin[2], margin[0]]);
let color = d3.scaleOrdinal().domain(sectors).range(d3.schemePaired);
let marketcapDomain = d3.extent(data.map((d) => +d["Market Cap"]));
let size = d3.scaleSqrt().domain(marketcapDomain).range([3, 40]);
svg
.selectAll(".circ")
.data(data)
.enter()
.append("circle")
.attr("class", "circ")
.attr("stroke", "black")
.attr("fill", (d) => color(d.Sector))
.attr("r", (d) => size(d["Market Cap"]))
.attr("cx", (d) => xScale(d.Sector))
.attr("cy", (d) => yScale(d.Return));
let simulation = d3
.forceSimulation(data)
.force(
"x",
d3
.forceX((d) => {
return xScale(d.Sector);
})
.strength(0.2)
)
.force(
"y",
d3
.forceY(function (d) {
return yScale(d.Return);
})
.strength(1)
)
.force(
"collide",
d3.forceCollide((d) => {
return size(d["Market Cap"]);
})
)
.alphaDecay(0)
.alpha(0.3)
.on("tick", tick);
function tick() {
d3.selectAll(".circ")
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y);
}
let init_decay = setTimeout(function () {
console.log("start alpha decay");
simulation.alphaDecay(0.1);
}, 3000);
});
</script>