D3 sparkline 01
by aybalasubramanian
November 16, 2018
HTML
<p>This will produce the first examples you saw at the top, like this <span id="spark1"></span>. If you are interested in what you should or shouldn't do in sparkline, I would recommend </p>
CSS
#spark1{
}
svg{
}
.sparkline {
fill: none;
stroke: #888888;
stroke-width: 1px;
}
.sparkcircle {
fill: #ff0000;
stroke: none;
}
.sparkrange{
fill: #dddddd;
stroke: none;
}
JavaScript
var width = 100;
var height = 21;
var x = d3.scale.linear().range([0, width - 2]);
var y = d3.scale.linear().range([height - 4, 0]);
var parseDate = d3.time.format("%b %d, %Y").parse;
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
function sparkline(elemId, data, lo, hi) {
data.forEach(function(d) {
d.date = parseDate(d.Date);
d.close = +d.Close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
var svg = d3.select(elemId)
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(0, 2)');
if (lo && hi){
svg.append('rect')
.attr('class', 'sparkrange')
.attr("x", x(data[0].date))
.attr("y", y(hi))
.attr("width", x(data[data.length - 1].date) - x(data[0].date))
.attr("height", y(lo) - y(hi));
}
svg.append('path')
.datum(data)
.attr('class', 'sparkline')
.attr('d', line);
svg.append('circle')
.attr('class', 'sparkcircle')
.attr('cx', x(data[data.length - 1].date))
.attr('cy', y(data[data.length - 1].close))
.attr('r', 1.5);
}
var data = [
{"Date": "Feb 1, 2014", "Close": "26"},
{"Date": "Feb 2, 2014", "Close": "27"},
{"Date": "Feb 3, 2014", "Close": "29"},
{"Date": "Feb 4, 2014", "Close": "23"},
{"Date": "Feb 5, 2014", "Close": "22"},
{"Date": "Feb 8, 2014", "Close": "24"},
{"Date": "Feb 9, 2014", "Close": "29"},
{"Date": "Feb 10, 2014", "Close": "26"},
{"Date": "Feb 11, 2014", "Close": "25"}
];
sparkline('#spark1', data, 24.3, 25.6);