D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
AlxClt
Full window
Github gist
TP2
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; } </style> </head> <body> <script> // Margin setup var margin = {top: 20, right: 20, bottom: 20, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // Basic SVG canvas var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //mappings var symb={'setosa':d3.symbolCross,'versicolor':d3.symbolStar,'virginica':d3.symbolWye} var col={'setosa':'red','versicolor':'yellow','virginica':'orange'} //data d3.csv('iris.csv', function(error,data){ data.forEach(function(d) { d.sepal_length = +d.sepal_length; d.sepal_width = +d.sepal_width;}); //scales var x = d3.scaleLinear() .range([0,width]) .domain(d3.extent(data, function(d) { return d.sepal_length; })); var y = d3.scaleLinear() .range([height,0]) .domain([0, d3.max(data, function(d) { return d.sepal_width; })]); //axis var xAxis = d3.axisBottom(x) var yAxis = d3.axisLeft(y) svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") //line var trend=trend_line(data); var line = d3.line() .x(function(d) { return x(d.x); }) .y(function(d) { return y(d.yhat); }); svg.append("path") .datum(trend) .attr("class", "line") .attr("d", line) .style("stroke-width",2) .style('stroke','green'); var paths=svg.selectAll('path').data(data) .enter() .append('path') .attr('class','symbol') .attr("d", d3.symbol().type(function(d){return symb[d.species] })) .attr("transform", function(d) { return "translate(" + x(d.sepal_length) + ",+" + y(d.sepal_width) + ")";}) .style('fill',function(d) {return col[d.species]}); }) function trend_line(data) { var x = []; var y = []; data.map(function(d) { x.push(d.sepal_length); y.push(d.sepal_width); }); var n = x.length; var x_mean = 0; var y_mean = 0; var term1 = 0; var term2 = 0; // compute means for (var i = 0; i < n; i++) { x_mean += x[i] y_mean += y[i] } // calculate mean x and y x_mean /= n; y_mean /= n; // calculate coefficients var xr = 0; var yr = 0; for (i = 0; i < x.length; i++) { xr = x[i] - x_mean; yr = y[i] - y_mean; term1 += xr * yr; term2 += xr * xr; } var b1 = term1 / term2; var b0 = y_mean - (b1 * x_mean); // perform regression yhat = []; // fit line using coeffs for (i = 0; i < x.length; i++) { yhat.push(b0 + (x[i] * b1)); } var data = []; for (i = 0; i < y.length; i++) { data.push( {"yhat": yhat[i], "x": x[i] }) } return (data); }; </script> </body>
https://d3js.org/d3.v4.min.js