Created
November 9, 2012 11:45
-
-
Save Petrlds/4045315 to your computer and use it in GitHub Desktop.
D3 transitions on enter/update/remove
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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