Skip to content

Instantly share code, notes, and snippets.

@mukhtyar
Last active March 24, 2016 21:47
Show Gist options
  • Save mukhtyar/d29605757190f60c555a to your computer and use it in GitHub Desktop.
Save mukhtyar/d29605757190f60c555a to your computer and use it in GitHub Desktop.
Simple D3 Bar Chart with Transitions
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:500px; height: 500px; margin-left: 100px; }
button {padding: 10px;}
</style>
</head>
<body>
<div>
<button id="data1">Set Data to dataset1</button>
<button id="data2">Set Data to dataset2</button>
</div>
<script>
var svg = d3.select("body").append("svg")
.attr({height: 300, width: 500})
.style("background-color", 'gray');
var dataset1 = [{value: 30}, {value: 55}, {value: 34}];
var dataset2 = [{value: 60}, {value: 25}, {value: 120}, {value: 50}];
// Wrapping the code inside a function so we can reuse it
function renderBars(data) {
var selection = svg.selectAll("rect")
.data(data);
// enter
selection.enter()
.append("rect");
// exit
selection
.exit()
.transition()
.delay(100)
.duration(300)
.style({ fill: "yellow"})
.remove();
// update
selection
.transition()
.duration(300)
.ease('bounce')
.attr("height", function(d){
return d.value; }) //Just the data value
.attr("x", function(d, i){
return (i * 100); }) //width + 20px spacing
.attr({width: 80})
.attr("y", function(d){
return (300 - d.value); }) //Svg height minus data value
.style({ fill: "#a72d1a"});
}
// code for buttons
d3.select("#data1")
.on("click", function(d,i) {
renderBars(dataset1);
});
d3.select("#data2")
.on("click", function(d,i) {
renderBars(dataset2);
});
// First time it draws
renderBars(dataset1);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment