Sparklines in D3.js

17 July 2018

A sparkline is a very small chart that shows a value change over some controlling factor, usually time. Sparklines typically do not have axes or labels, and should be self-explanatory given the context of the sparkline.

This is an example sparkline. It is a small graphical object, in the body of the page. It is meant to help narrate a story that your data is trying to tell. Creating this sparkline is quite easy.

constsparkline=(container,data,options)=>{constdefaults={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]}};// Apply defaults to the given options.options=$.extend(true,defaults,options);// Add an SVG object to the given container.letsvg=d3.select(container).append("svg").classed("sparkline",true).classed("sparkline-svg",true).attr("width",options.size[0]).attr("height",options.size[1]);letg=svg.append("g").classed("sparkline",true).classed("sparkline-group",true);letxScale=options.scale.x.range([0,options.size[0]]).domain(d3.extent(data,options.value.x));letyScale=options.scale.y.range([options.size[1],0]).domain(d3.extent(data,options.value.y));// Create the line generator function.letline=d3.line().x(d=>xScale(options.value.x(d))).y(d=>yScale(options.value.y(d)));// Finally, draw the path object.letpath=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);returnpath;};