Skip to content

Instantly share code, notes, and snippets.

@Petrlds
Created November 9, 2012 11:45
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 Petrlds/4045315 to your computer and use it in GitHub Desktop.
Save Petrlds/4045315 to your computer and use it in GitHub Desktop.
D3 transitions on enter/update/remove
<!DOCTYPE html>
<html>
<head>
<title></title>
<!--<link href="css/nv.d3.css" rel="stylesheet">-->
<script src="lib/d3.v2.js" type="text/javascript" charset="utf-8"></script>
<!--<script src="lib/nv.d3.js" type="text/javascript" charset="utf-8"></script>-->
<style>
#chart svg {
height: 500px;
width: 500px;
}
</style>
</head>
<body>
<div id="chart">
<svg></svg>
</div>
<script>
var color = d3.scale.category20c();
var container = d3.select('#chart svg');
var randomFromTo = function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
};
var newData = function() {
var nD = [];
for(var i = 0; i < randomFromTo(4, 18); i++) {
nD.push({
"x": randomFromTo(10, 200),
"y": randomFromTo(10, 100),
"r": randomFromTo(5, 20)
});
}
return nD;
};
var test = function(data) {
var draw = function(selection) {
selection
.attr("r", function(d, i) { return d.r; })
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
};
var circle = container.selectAll("circle")
.data(data, function(d, i) { return i; });
circle.enter().append("circle")
.attr("r", 0)
.attr("fill", function(d, i) { return color(i); })
.transition().duration(1000).call(draw);
circle.transition().duration(1000)
.ease("elastic")
.call(draw);
circle.exit()
.transition().duration(1000)
.attr("r", 0)
.remove();
};
test(newData());
// iterate with new data every 3 sec
setInterval(function() {
test(newData());
}, 3000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment