D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
allyraza
Full window
Github gist
fresh block 123
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> <svg width="800" height="140" id="ex4"> </svg> <button class="add">Add</button> <button class="remove">Remove</button> <script> var cities = [ {name: 'London', population: 8416500, continent: 'Europe'}, {name: 'New York City', population: 8419000, continent: 'North America'}, {name: 'Paris', population: 2241000, continent: 'Europe'}, {name: 'Tokyo', population: 13297000, continent: 'Asia'}, ]; var radiusScale = d3.scaleSqrt() .domain([0, 25000000]) .range([0, 50]) ; var color = d3.scaleOrdinal(d3.schemeCategory20c); const svg = d3.select('body') .append('svg') .attr('width', 1000) .attr('height', 500) .append('g') .attr('transform', `translate(${100},${100})`) ; function update(data) { // Perform the data join var selection = svg .selectAll('circle') .data(data); // Remove surplus elements selection.exit() .remove(); // Add new elements let circle = selection.enter() .append('circle'); // Update existing AND new elements circle.attr('r', function(d) { return radiusScale(d.population); }) .attr('cx', (d, i) => i * 100) .style('fill', (d) => clor(d.continent)) ; } function rand(min=100000, max=100000000) { return (Math.random() * (max - min) + min); } update(cities); document.querySelector('.add').addEventListener('click', function() { cities.push( {name: 'Shanghai', population: rand(), continent: 'Asia'} ); update(cities); }); document.querySelector('.remove').addEventListener('click', function() { cities.pop(); update(cities); }); </script> </body>
https://d3js.org/d3.v4.min.js