-
Notifications
You must be signed in to change notification settings - Fork 34
/
d3-line-chart-boilerplate.html
149 lines (121 loc) · 4.64 KB
/
d3-line-chart-boilerplate.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
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
<!DOCTYPE html>
<meta charset=utf-8>
<style>
body {
margin: 0 auto;
padding: 1em;
max-width: 1000px;
}
svg text { font: 15px 'Liberation Sans', 'Luxi Sans', sans-serif; }
.axis text { fill: black; }
.line { fill: none; stroke: steelblue; stroke-width: 1.5px; }
.mark { stroke: red; }
.grid line { stroke: #ddd; }
.grid .domain { stroke: none; }
.overlay { fill: none; pointer-events: all; }
.focus circle { fill: none; stroke: steelblue; }
.focus tspan { paint-order: stroke; stroke: white; stroke-width: 10px; }
</style>
<body>
<script>
'use strict'
let d3js_ver = 7,
d3js_local_url = `d3.v${d3js_ver}.min.js`,
d3js_remote_load = true, // false = always use local copy
d3js_remote_url = `https://d3js.org/d3.v${d3js_ver}.min.js`,
d3js_remote_import = `https://cdn.jsdelivr.net/npm/d3@${d3js_ver}/+esm`,
d3js_loader = async () => {
if (window.d3) return window.d3
let res = await fetch(d3js_local_url).catch(res => res)
if (res.ok) { eval(await res.text()); return window.d3 }
if (!d3js_remote_load) return console.log(
`WARNING: Failed to load local d3.js`
+ ` [ ${d3js_local_url} ]: ${res.status} - ${res.statusText}` )
console.log(`WARNING: importing d3 from ${d3js_remote_import}`)
return await import(d3js_remote_import) }
window.onload = () => d3js_loader().then(d3 => {
if (!d3) return document.body.innerHTML = `
<h2>ERROR: failed to load d3.js library</h2>
<p>Check uMatrix/NoScript/adblocker setttings or download
<a href='${d3js_remote_url}'>${d3js_local_url}</a> into same dir as this html.</p>`
// Data
let data = [], offset = 0, offset_max = 3 * 3600 / 59
while (offset <= offset_max) {
let chance = 0.05, chance_neg = 1 - chance,
state = !data.length ? chance_neg : data[data.length-1].state * chance_neg
data.push({offset: offset, state: state})
offset += 1
}
// Basic d3 boilerplate
let
margin = {top: 50, right: 100, bottom: 50, left: 100},
width = 960 - margin.left - margin.right,
height = 700 - margin.top - margin.bottom,
x = d3.scaleLinear().range([0, width]),
y = d3.scaleLinear().range([height, 0])
let vis = 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})`)
// Axes and chart
let kx = 'offset', ky = 'state',
line = d3.line().x(d => x(d[kx])).y(d => y(d[ky]))
let attrs = vals => s => { // set bunch of attributes from dict
Object.entries(vals).forEach(([k,v]) => s.attr(k, v)) }
x.domain(d3.extent(data, d => d[kx]))
y.domain(d3.extent(data, d => d[ky]))
vis
.call(s => {
s.append('g').attr('class', 'x grid').call(
d3.axisBottom(x).tickSize(height, 0).tickFormat('') )
s.append('g').attr('class', 'y grid').call(
d3.axisLeft(y).tickSize(-width, 0).tickFormat('') ) })
.call( s => s
.append('g')
.attr('class', 'x axis').attr('transform', `translate(0,${height})`)
.call(d3.axisBottom(x))
.append('text')
.attr('transform', `translate(${width},0)`)
.attr('dx', '-1em').attr('dy', '3em')
.style('text-anchor', 'end').text(kx) )
.call( s => s
.append('g').attr('class', 'y axis').call(d3.axisLeft(y))
.append('text')
.attr('transform', 'rotate(-90)').attr('dx', '-1em').attr('dy', '-3em')
.style('text-anchor', 'end').text(ky) )
.call(s => s.append('path').data([data]).attr('class', 'line') .attr('d', line))
vis.append('line').attr('class', 'mark')
.call(attrs({x1: x(50), x2: x(50), y1: 0, y2: height}))
// Focus data on mouseover
let side = -1, // 1 or -1
x_bisect = d3.bisector(d => d[kx]).left,
focus = vis
.append('g').attr('class', 'focus').style('display', 'none')
.call(s => s.append('circle').attr('r', 4.5)),
focus_label = focus.append('text')
.attr('x', 10).attr('dy', '.3em')
.attr('text-anchor', side > 0 ? 'start' : 'end')
let format_n = d3.format(',.3f'),
format = (k, v) => {
if (k == kx) return v
if (k == ky) return format_n(v)
return (typeof v === 'number') ? format_n(v) : v }
vis.append('rect')
.attr('class', 'overlay').attr('width', width).attr('height', height)
.on('mouseover', (ev, d) => focus.style('display', null))
.on('mouseout', (ev, d) => focus.style('display', 'none'))
.on('mousemove', (ev, d) => {
let x0 = x.invert(d3.pointer(ev)[0]),
i = x_bisect(data, x0, 1), d0 = data[i-1], d1 = data[i]
d = x0 - d0[kx] > d1[kx] - x0 ? d1 : d0
focus.attr('transform', `translate(${x(d[kx])},${y(d[ky])})`)
focus_label.selectAll('tspan').call( s => s
.data(Object.entries(d).map(([k, v]) => `${k}: ${format(k, v)}`).sort())
.join(
en => en.append('tspan').attr('dy', '1.5em').attr('x', `${side}em`),
upd => upd.text(d => d), ex => ex.remove() ) ) })
})
</script>
</body>