D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Ronolibert
Full window
Github gist
animate axis and data
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="UTF-8"> <script src="//d3js.org/d3.v4.min.js"></script> <style> .chart { background: lightgray; border: 1px solid black; } rect { fill: steelblue; } </style> </head> <body> <div class="chart"></div> <button onclick="render('math')">Math</button> <button onclick="render('science')">Science</button> <button onclick="render('language')">Language</button> <script> var data = [ {name: 'Alice', math: 37, science: 62, language: 54}, {name: 'Billy', math: null, science: 34, language: 85}, {name: 'Cindy', math: 86, science: 48, language: null}, {name: 'David', math: 144, science: null, language: 65}, {name: 'Emily', math: 59, science: 55, language: 29} ]; var margin = { top: 10, right: 10, bottom: 30, left: 30 }; var width = 400 - margin.left - margin.right; var height = 535 - margin.top - margin.bottom; var svg = d3.select('.chart') .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', `translate(${margin.left}, ${margin.top})`); var xScale = d3.scaleBand() .domain(data.map(d => d.name)) .range([0, width]) .padding(0.2); svg .append('g') .attr('transform', `translate(0, ${height})`) .call(d3.axisBottom(xScale)); var yScale = d3.scaleLinear() .domain([0, 100]) .range([height, 0]); var yAxis = svg .append('g') .call(d3.axisLeft(yScale)); function render (subject = 'math') { var t = d3.transition().duration(1000); var update = svg.selectAll('rect') .data(data.filter(d => d[subject]), d => d.name); update.exit() .transition(t) .attr('y', height) .attr('height', 0) .remove(); yScale.domain([0, d3.max(data, d => d[subject])]); yAxis .transition(t) .delay(1000) .call(d3.axisLeft(yScale)); update .transition(t) .delay(1000) .attr('y', d => yScale(d[subject])) .attr('height', d => height - yScale(d[subject])); update .enter() .append('rect') .attr('y', height) .attr('height', 0) .attr('x', d => xScale(d.name)) .attr('width', d => xScale.bandwidth()) .transition(t) .delay(update.exit().size() ? 2000 : 0) .attr('y', d => yScale(d[subject])) .attr('height', d => height - yScale(d[subject])); } render(); </script> </body>
https://d3js.org/d3.v4.min.js