D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
RobertDelgado
Full window
Github gist
Rob's scatter plot
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> var myData = [ {x:3, y:2, cat:"a"}, {x:7, y:6, cat:"b"}, {x:2, y:8, cat:"b"}, {x:5, y:7, cat:"a"} ]; var colorMap = { a:"red", b:"blue" }; //Setting up x and y scales var pointRadius = 4; var xAxisName = "x"; var yAxisName = "y"; var colorLookup = "cat" var margin = {left: 20, right: 20, top: 20, bottom: 20}; var outerWidth = 250; var innerWidth = outerWidth - margin["left"] - margin["right"]; var outerHeight = 250; var innerHeight = outerHeight - margin["top"] - margin["bottom"]; var svg = d3.select("body").append("svg").attr("width", outerWidth).attr("height", outerHeight); var g = svg.append("g").attr("transform", "translate(" + margin["left"] + "," + margin["top"] +")"); var xAxisG = g.append("g").attr("transform", "translate(0," + innerHeight + ")"); var yAxisG = g.append("g"); function render(data, x_input, y_input){ var max_x = d3.max(myData, function(d){return d[xAxisName];}); var max_y = d3.max(myData, function(d){return d[yAxisName];}); var xScale = d3.scaleLinear().range([0,innerWidth]).domain([0,max_x]); var yScale = d3.scaleLinear().range([innerHeight,0]).domain([0,max_y]); var xAxis = d3.axisBottom().scale(xScale).tickPadding(2);//.tickSize(-innerWidth); var yAxis = d3.axisLeft().scale(yScale).tickPadding(2);//.tickSize(-innerHeight); xAxisG.append("text").attr(x_input, -innerWidth/2).attr(y_input, 100); yAxisG.append("text").attr(x_input, innerHeight/2).attr(y_input, 60).attr("transform", `rotate(-90)`); xScale.domain([0, max_x]); yScale.domain([0,max_y]); xAxisG.call(xAxis); yAxisG.call(yAxis); //var circs = svg.selectAll("circle").data(data); var circs = g.selectAll("circle").data(data); circs.enter().append("circle") .attr("r",pointRadius) .attr("fill", function(d){return (colorMap[d[colorLookup]]);}) .attr("cx", function(d){return(xScale(d[x_input]));}) .attr("cy", function(d){return(yScale(d[y_input]));}); circs.exit().remove(); }; render(myData, "x", "y"); //setTimeout(function(){render(myData[0,1]);}, 1000); //setTimeout(function(){render(myData[0,1,2]);}, 1000); </script> </body>
https://d3js.org/d3.v4.min.js