D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
TollyCoburn
Full window
Github gist
Scatter Transition
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> <p>Click on this text to update the chart with new data values as many times as you like!</p> <script> //Width and height var w = 700; var h = 400; var padding = 30; //Dynamic, random dataset var dataset = []; var numDataPoints = 50; var maxRange = Math.random() * 1000; for (var i = 0; i < numDataPoints; i++) { var newNumber1 = Math.floor(Math.random() * maxRange); var newNumber2 = Math.floor(Math.random() * maxRange); dataset.push([newNumber1, newNumber2]); } //Create scale functions var xScale = d3.scaleLinear() .domain([0, d3.max(dataset, function(d) { return d[0]; })]) .range([padding, w - padding * 2]); var yScale = d3.scaleLinear() .domain([0, d3.max(dataset, function(d) { return d[1]; })]) .range([h - padding, padding]); //Define X axis var xAxis = d3.axisBottom() .scale(xScale) .ticks(5); //Define Y axis var yAxis = d3.axisLeft() .scale(yScale) .ticks(5); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); //Create circles svg.selectAll("circle") .data(dataset) .enter() .append("circle") .attr("cx", function(d) { return xScale(d[0]); }) .attr("cy", function(d) { return yScale(d[1]); }) .attr("r", 2); //Create X axis svg.append("g") .attr("class", "axis") .attr("transform", "translate(0," + (h - padding) + ")") .call(xAxis); //Create Y axis svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + padding + ",0)") .call(yAxis); //On click, update with new data d3.select("p") .on("click", function() { var numValues = dataset.length; var maxRange = Math.random() * 1000; dataset = []; for (var i = 0; i < numValues; i++) { var newNumber1 = Math.floor(Math.random() * maxRange); var newNumber2 = Math.floor(Math.random() * maxRange); dataset.push([newNumber1, newNumber2]); } //Update scale domains xScale.domain([0, d3.max(dataset, function(d) { return d[0]; })]); yScale.domain([0, d3.max(dataset, function(d) { return d[1]; })]); //Update all circles svg.selectAll("circle") .data(dataset) .transition() .duration(1000) .attr("cx", function(d) { return xScale(d[0]); }) .attr("cy", function(d) { return yScale(d[1]); }); }); </script> </body>
https://d3js.org/d3.v4.min.js