-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
98 lines (88 loc) · 2.56 KB
/
index.html
File metadata and controls
98 lines (88 loc) · 2.56 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 Bar Chart</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
#tooltip {
position: absolute;
background: rgba(0,0,0,0.7);
color: white;
padding: 8px;
border-radius: 4px;
pointer-events: none;
opacity: 0;
}
text {
font-size: 10px;
}
</style>
</head>
<body>
<h1 id="title">United States GDP</h1>
<div id="tooltip"></div>
<script>
const url = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json';
fetch(url)
.then(response => response.json())
.then(data => {
const dataset = data.data;
const w = 800;
const h = 400;
const padding = 60;
const svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h);
const xScale = d3.scaleTime()
.domain([new Date(dataset[0][0]), new Date(dataset[dataset.length-1][0])])
.range([padding, w - padding]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, d => d[1])])
.range([h - padding, padding]);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
svg.append('g')
.attr('id', 'x-axis')
.attr('transform', `translate(0, ${h - padding})`)
.call(xAxis);
svg.append('g')
.attr('id', 'y-axis')
.attr('transform', `translate(${padding},0)`)
.call(yAxis);
svg.selectAll('.bar')
.data(dataset)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('data-date', d => d[0])
.attr('data-gdp', d => d[1])
.attr('x', d => xScale(new Date(d[0])))
.attr('y', d => yScale(d[1]))
.attr('width', (w - 2*padding) / dataset.length)
.attr('height', d => h - padding - yScale(d[1]))
.on('mouseover', (event, d) => {
const tooltip = d3.select('#tooltip');
tooltip.style('opacity', 1)
.style('left', (event.pageX + 10) + 'px')
.style('top', (event.pageY - 25) + 'px')
.attr('data-date', d[0])
.html(`${d[0]}<br>$${d[1]} Billion`);
})
.on('mouseout', () => {
d3.select('#tooltip').style('opacity', 0);
});
});
</script>
</body>
</html>