Skip to content

Instantly share code, notes, and snippets.

@ckothari
Created August 9, 2016 14:21
Show Gist options
  • Save ckothari/699b112b6e1376779e65973bbabdced6 to your computer and use it in GitHub Desktop.
Save ckothari/699b112b6e1376779e65973bbabdced6 to your computer and use it in GitHub Desktop.
Bar chart with data joins
<html>
<head>
<!--<script type="application/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>-->
<script type="application/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.1/d3.js"></script>
</head>
<body>
<!-- Visualization Placeholder -->
<div id="bar-chart"></div>
<!--Adopted from https://bl.ocks.org/mbostock/7341714-->
<script type="application/javascript">
var width = 420,
barheight = 30;
var svg = d3.select('#bar-chart')
.append('svg')
.attr('width', width + 50)
.attr('height', 1000);
var scale = d3.scaleLinear()
.range([0, width]);
function createBar(data) {
scale.domain([0, d3.max(data)]);
var barGroups = svg.selectAll('g')
.data(data, function(d){return d;});
barGroups.exit().remove();
var enterGroup = barGroups.enter() //ENTER
.append('g');
enterGroup.append('rect')
.attr('class', 'bar')
.attr('height', barheight - 1)
.attr('fill', 'steelblue');
enterGroup.append('text')
.attr('class', 'text')
.attr("y", barheight / 2)
.attr("dy", ".35em");
var mergedGroups = enterGroup.merge(barGroups)
.attr("transform", function(d, i){
return "translate(0, " + barheight * i + ")";
});
mergedGroups.selectAll('rect')
.attr('width', function(d){
return scale(d);
});
mergedGroups.selectAll('text')
.attr("x", function(d) { return scale(d) + 10; })
.text(function(d) { return d;});
}
var data = [
[10, 20, 30],
[10, 20, 40],
[10, 20, 200, 500],
[50, 20, 10],
[50, 20, 10, 1000, 5000]
];
function start(counter){
if(counter < data.length){
setTimeout(function(){
counter++;
createBar(data[counter]);
start(counter);
}, 1000);
}
}
start(0);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment