D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
giguerre
Full window
Github gist
Regression
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>D3 Scatterplot et scatter plot </title> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> // margin definition var margin = {top: 20, right: 20, bottom: 30, left: 40}, widthm = 1000, heightm = 500; // graph dimention var gf_w = widthm -margin.left - margin.right; var gf_h = heightm - margin.top - margin.bottom; // Get data // variables var Iris_setosa_x=[], Iris_setosa_y =[], Iris_virginica_x =[], Iris_virginica_y=[], Iris_vrscolor_x=[], Iris_vrscolor_y=[]; var iris; d3.csv("iris.csv", function(data) { iris = data; data.forEach(function(d){ if (d["species"] == "virginica") { Iris_virginica_x.push(+d.petal_length) Iris_virginica_y.push(+d.sepal_length) } else if (d["species"] == "setosa") { Iris_setosa_x.push(+d.petal_length) Iris_setosa_y.push(+d.sepal_length) } else { Iris_vrscolor_x.push(+d.petal_length) Iris_vrscolor_y.push(+d.sepal_length) } }) // linear regression function function regression(xdt, ydt) { var TSum = function(xi, xj) { return xi + xj; }; var xmean = xdt.reduce(TSum) * 1.0 / xdt.length; var ymean = ydt.reduce(TSum) * 1.0 / ydt.length; var xcovar = xdt.map(function(d) { return Math.pow(d - xmean, 2); }) .reduce(TSum); var ycovar = ydt.map(function(d) { return Math.pow(d - ymean, 2); }) .reduce(TSum); var xycovar = ydt.map(function(d, i) { return (d - ymean) * (xdt[i] - xmean); }) .reduce(TSum); var delta = xycovar / xcovar; var b = ymean - (xmean * delta); return [delta, b]; } // scale var xScale = d3.scaleLinear() .domain([d3.min(iris, function(d) { return d["sepallength"]; }), d3.max(iris, function(d) { return d["sepallength"]; })]) .range([0, gf_w]); var yScale = d3.scaleLinear() .domain([d3.min(iris, function(d) { return d["sepalwidth"]; }), d3.max(iris, function(d) { return d["sepalwidth"]; })]) .range([gf_h, 0]); // svp creation var svg = d3.select("svg") .attr("width", widthm + margin.left+ margin.right) .attr("height", heightm + margin.top + margin.bottom) .append("g"); //getting the parameter of regression line var setosa = regression(Iris_setosa_x, Iris_setosa_y); var virginica = regression(Iris_virginica_x, Iris_virginica_y); var vrscolor = regression(Iris_vrscolor_x, Iris_vrscolor_y); // setosa parametr var x1_s = xScale(0), y1_s = setosa[0] * x1_s + setosa[1], x2_s = xScale(d3.max(iris, function(d) { return d.sepal_length; })), y2_s = setosa[0] * x2_s + setosa[1]; // graphe // regression line //setosa svg.append("line") .style("stroke", "blue") .attr("x1", x1_s ) .attr("y1" , y1_s) .attr("x2", x2_s ) .attr("y2", y2_s); // dosen't work >< blocked here }); </script> </body>
https://d3js.org/d3.v4.min.js