D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Soorin
Full window
Github gist
Simple bar chart 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; } svg{ width: 960px; height: 400px; } </style> </head> <body> <svg></svg> <p>Select new value set</p> <select id="changeBars"> <option value="0">First Set<option> <option value="1">Second Set<option> <option value="2">Third Set<option> </select> <script> const dataValues = [[20, 45, 150, 220], [90, 100, 230, 30, 190], [50, 150, 200]]; const trans = d3.transition().duration(1000); const colors = d3.scaleOrdinal(d3.schemeCategory10); const height = 300; const rectWidth = 100; const svg = d3.select('svg'); function updateBars(data){ var bars = svg.selectAll('rect') .data(data, d => d); //exit bars.exit().transition(trans) .attr('y', height) .attr('height', 0) .remove(); //enter const enter = bars.enter().append('rect') .attr('width', rectWidth) .attr('stroke', '#000') .attr('y', height); //enter and update bars = enter.merge(bars) .attr('x', (d, i) => i * rectWidth) .attr('fill', d => colors(d)) .transition(trans) .attr('y', d => height - d) .attr('height', d => d); }; updateBars(dataValues[0]); document.getElementById("changeBars").addEventListener('change', (event) => { updateBars(dataValues[event.target.value]); }); </script> </body>
https://d3js.org/d3.v4.min.js