/
sparkline.js
85 lines (69 loc) · 2.09 KB
/
sparkline.js
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
// https://raw.githubusercontent.com/jarrettmeyer/jarrettmeyer.github.io/master/assets/js/sparkline.js
const randBetween = (min, max) => {
let range = max - min;
return min + range * Math.random();
}
const sparkline = (container, data, options) => {
const defaults = {
scale: {
x: d3.scaleLinear(),
y: d3.scaleLinear()
},
size: [100, 40],
style: {
stroke: "rgb(60, 120, 240)",
strokeWidth: 1
},
value: {
x: d => d[0],
y: d => d[1]
}
};
options = $.extend(true, defaults, options);
let svg = d3.select(container)
.append("svg")
.classed("sparkline", true)
.classed("sparkline-svg", true)
.attr("width", options.size[0])
.attr("height", options.size[1]);
let g = svg.append("g")
.classed("sparkline", true)
.classed("sparkline-group", true);
let xScale = options.scale.x
.range([0, options.size[0]])
.domain(d3.extent(data, options.value.x));
let yScale = options.scale.y
.range([options.size[1], 0])
.domain(d3.extent(data, options.value.y));
let line = d3.line()
.x(d => xScale(options.value.x(d)))
.y(d => yScale(options.value.y(d)));
let path = g.append("path")
.classed("sparkline", true)
.classed("sparkline-path", true)
.datum(data)
.attr("d", line)
.style("fill", "none")
.style("stroke", options.style.stroke)
.style("stroke-width", options.style.strokeWidth);
return path;
};
// Set constants that will be used
const duration = 30;
const myData = [];
const now = Date.now();
let myContainer = document.getElementById("sparkline-container");
let myOptions = {
size: [100, 20],
value: {
x: d => d.date,
y: d => d.value
}
};
for (let i = duration; i > 0; i--) {
myData.push({
date: new Date(now - (i * 24 * 60 * 60 * 1000)),
value: randBetween(10, 20)
});
}
sparkline(myContainer, myData, myOptions);