D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
EranM6
Full window
Github gist
scatter
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="data.js"></script> <script src="data2.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> const width = 960; const height = 500; const margin = { left: 40, right: 20, top: 20, bottom: 20}; var svg = d3.select('body').append('svg') .attr('width', width) .attr('height', height) const xScale = d3.scaleLinear() .range([margin.left, width - margin.right]) const yScale = d3.scaleLinear() .range([height - margin.bottom, margin.top ]) const x = svg.append('g') .attr('transform', `translate(0, ${margin.top})`); const y = svg.append('g') .attr('transform', `translate(${margin.left}, 0)`); const graph = svg.append('g') const redLine = svg.append('line'); const createGraph = data => { const t = d3.transition().duration(3000); xScale.domain([ d3.min(data, d => d.value[0].x)-3000, d3.max(data, d => d.value[0].x)+3000 ]); yScale.domain([ d3.min(data, d => d.value[0].y)-1, d3.max(data, d => d.value[0].y)+1 ]); let scatter = graph.selectAll('circle') .data(data, (d,i) => i); const enter = scatter.enter().append('circle') .attr('r', 0); scatter.exit() .transition(t) .attr('r', 0) .remove() scatter = enter.merge(scatter) .attr('fill', d => d.value[0].y > 0 ? 'green' : 'red') .transition(t) .attr('cx', d => xScale(d.value[0].x)) .attr('cy', d => yScale(d.value[0].y)) .attr('r', 5); redLine .attr('x1', xScale(xScale.domain()[0])) .attr('x2', xScale(xScale.domain()[1])) .attr('y1', yScale(0)) .attr('y2', yScale(0)) .attr('stroke-width', 3) .attr('stroke', 'red') const xAxis = d3.axisTop().scale(xScale); const yAxis = d3.axisLeft().scale(yScale); x.call(xAxis); y.call(yAxis); } createGraph(data2) setTimeout(() => { data2.forEach(d => { d.x = +d.x; d.y = +d.y; }); createGraph(data1); }, 3000) </script> </body>
https://d3js.org/d3.v4.min.js