D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
AlexDaGr8
Full window
Github gist
JS created regression line
js created regression line of a friends Zwift ride.
<!DOCTYPE html> <body> <div id="chart"></div> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var margin = 40, width = 960 - margin*2, height = 500 - margin*2; var svg = d3.select('#chart').append('svg') .attr('width', width + margin*2) .attr('height', height + margin*2) .append('g') .attr('transform', 'translate(' + [margin,margin] + ')'); d3.csv("cycling.csv", function(d) { return d.cadence > 20 ? d : null; }, function(err,data) { if (err) console.log(err); console.log(data) data.forEach(function(d,i) { d.altitude = +d.altitude; d.cadence = +d.cadence; d.distance = +d.distance; d.power = +d.power; d.slope = +d.slope; d.speed = +d.speed; }); var x = d3.scaleLinear() .range([0,width]) .domain([0, d3.max(data, function(d) { return d.speed; })]) var y = d3.scaleLinear() .range([height,0]) .domain([0, d3.max(data, function(d) { return d.cadence; })]) var line = d3.line() .x(function(d) { return x(d.x); }) .y(function(d) { return y(d.y); }) svg.append('g') .append('text') .attr('class', 'text') .text('Cadence') .attr('transform', 'translate(' + [-margin/2 - 5, height/2] + ') rotate(-90)') svg.append('g') .append('text') .attr('class', 'text') .text('Speed') .attr('transform', 'translate(' + [width/2, height + margin/2 + 5] + ')') svg.append('g') .attr('transform', 'translate(0,' + height + ')') .call(d3.axisBottom(x)); svg.append('g') .call(d3.axisLeft(y)); var circles = svg.selectAll('circle') .data(data) .enter().append('circle'); circles.attr('cx', function(d) { return x(d.speed); }) .attr('cy', function(d) { return y(d.cadence); }) .attr('r', 2); svg.append('path') .datum(regressionLine(data)) .attr('fill', 'none') .attr('stroke', 'steelblue') .attr('d', line) }); function regressionLine(data) { var ab = findRegressionLine(data); var b = ab[0], m = ab[1]; var arr = []; for (var i = 0; i < data.length; i++) { arr.push({x:i,y:b + (m * i)}); } return arr; } function findRegressionLine(data) { var sumX = d3.sum(data, function(d) { return d.speed; }) var sumY = d3.sum(data, function(d) { return d.cadence; }) var sumX2 = d3.sum(data, function(d) { return d.speed * d.speed; }) var sumY2 = d3.sum(data, function(d) { return d.cadence * d.cadence; }) var sumXY = d3.sum(data, function(d) { return d.speed * d.cadence; }) var n = data.length; var b = ((sumY * sumX2) - (sumX * sumXY)) / (n * (sumX2) - (sumX * sumX)); var m = (n * (sumXY) - (sumX * sumY)) / (n * sumX2 - (sumX * sumX)); return [b,m]; } </script> </body>
https://d3js.org/d3.v4.min.js