Simple D3 Bar Chart with Transitions - Bootcamp 2016
Built with blockbuilder.org
forked from mukhtyar's block: Simple D3 Bar Chart
Simple D3 Bar Chart with Transitions - Bootcamp 2016
Built with blockbuilder.org
forked from mukhtyar's block: Simple D3 Bar Chart
<!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> |