D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jrzief
Full window
Github gist
BasicSM
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } svg { border: solid 1px #333; margin: 5px;} .label { font-size: 20px; } .line { fill: none; stroke-width: 1.5px; stroke: #000000;} </style> </head> <body> <script> var height = 80, width = 140; var datapoints = [ { 'state': 'Alabama', 'measurements': [57, 62, 70, 77, 84, 90, 92, 92, 87, 78, 69, 60] }, { 'state': 'Alaska', 'measurements': [23, 27, 34, 44, 56, 63, 65, 64, 55, 40, 28, 25] }, { 'state': 'Arizona', 'measurements': [67, 71, 77, 85, 95, 104, 106, 104, 100, 89, 76, 66] }, { 'state': 'Arkansas', 'measurements': [51, 55, 64, 73, 81, 89, 92, 93, 86, 75, 63, 52] }, { 'state': 'California', 'measurements': [54, 60, 65, 71, 80, 87, 92, 91, 87, 78, 64, 54] }, { 'state': 'Colorado', 'measurements': [45, 46, 54, 61, 72, 82, 90, 88, 79, 66, 52, 45] }, { 'state': 'Connecticut', 'measurements': [37, 40, 47, 58, 68, 77, 82, 81, 74, 63, 53, 42] }, { 'state': 'Delaware', 'measurements': [43, 47, 55, 66, 75, 83, 87, 85, 79, 69, 58, 47] }, { 'state': 'Florida', 'measurements': [64, 67, 74, 80, 87, 91, 92, 92, 88, 81, 73, 65] } ] // y_scale: highs between 20 and 110 give us y values between 0 and 300 (height) // except you do it backwards because it's *distance from the top* var y_scale = d3.scaleLinear().domain([20,110]).range([height, 0]); // x_scale: use the index of the measurement, so 57 is 0, 62 is 1, etc // this is because it's per-month data, jan=0, dec=11 var x_scale = d3.scaleLinear().domain([0,11]).range([0, width]); var line = d3.line() .x(function(d, i) { return x_scale(i); }) .y(function(d) { return y_scale(d); }); // Treat an svg just like we would a circle - add one for every single data point var svgs = d3.select("body") .selectAll("svg") .data(datapoints) .enter() .append('svg') .attr("width", width) .attr("height", height); // Inside of each svg, draw your line svgs.append("path") .attr("class", "line") .attr("d", function(d) { return line(d['measurements']); }); svgs.append("text") .attr('class','label') .attr('x', width / 2) .attr('y', height - 5) .text( function(d) { return d['state']; }) .attr('text-anchor', 'middle') </script> </body>
https://d3js.org/d3.v4.min.js