Skip to content

Instantly share code, notes, and snippets.

@sxywu
Last active March 10, 2016 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sxywu/223cb837b32d6ed97cb8 to your computer and use it in GitHub Desktop.
Save sxywu/223cb837b32d6ed97cb8 to your computer and use it in GitHub Desktop.
Intro to D3 Live Coding
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
.label {
margin-left: 20px;
}
.update {
margin: 20px;
}
svg {
margin: 20px;
height: 500px;
display: block;
}
</style>
</head>
<body>
<span class="label label-default">Data</span> <span class="data"></span>
<button class='update btn btn-default'>update</button>
<svg></svg>
<script>
function randomData(length) {
var data = _.map(_.range(length), function() {
return _.random(1, 500);
});
$('.data').text(JSON.stringify(data));
return data;
}
var data = randomData(_.random(1, 10));
var g = d3.select('svg').append('g'),
color = d3.scale.category20(),
width = 20,
height = 500;
var rect = g.selectAll('rect')
.data(data).enter().append('rect')
.attr('x', function(d, i) {return i * width})
.attr('y', function(d) {return height - d})
.attr('width', width)
.attr('height', function(d) {return d})
.attr('fill', color);
$('.update').click(function() {
data = randomData(_.random(1, 10));
rect = g.selectAll('rect')
.data(data);
// enter new rect
rect.enter().append('rect');
// exit rect no longer needed
rect.exit().remove();
// update attributes on all the bars that still remain
rect.transition().duration(500)
.attr('x', function(d, i) {return i * width})
.attr('y', function(d) {return height - d})
.attr('width', width)
.attr('height', function(d) {return d})
.attr('fill', color);
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment