Skip to content

Instantly share code, notes, and snippets.

@Soorin
Created October 17, 2017 12:19
Show Gist options
  • Save Soorin/1506ad55b16b5bb54aee038fbec10425 to your computer and use it in GitHub Desktop.
Save Soorin/1506ad55b16b5bb54aee038fbec10425 to your computer and use it in GitHub Desktop.
Simple bar chart transition
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment