Skip to content

Instantly share code, notes, and snippets.

@kevlarr
Last active October 9, 2017 17:53
Show Gist options
  • Save kevlarr/35079f29b9fa318b30f471f71c6a9795 to your computer and use it in GitHub Desktop.
Save kevlarr/35079f29b9fa318b30f471f71c6a9795 to your computer and use it in GitHub Desktop.
Data transitions in D3 version 4

There is an excellent example of transitioning data in D3, but this only works in version 3.

D3 version 4 requires a slightly different approach, namely that the entered selections need to be merged prior to transition.

Added transition on exit. Also did a little code cleanup, especially given that eval is pretty gross.

<!doctype html>
<html>
<head>
<script src="http://d3js.org/d3.v4.min.js"></script>
<style>
button {
float: left;
}
svg {
height: 500px;
width: 500px;
}
circle {
fill: orange;
fill-opacity: 0.5;
stroke: orange;
}
line {
stroke: #ddd;
shape-rendering: crispEdges;
}
text {
text-anchor: middle;
}
</style>
</head>
<body>
<script>
var dataset = 0;
var data = [
[30, 35, 45, 55, 70],
[50, 55, 45, 35, 20, 25, 25, 40],
];
var lineLength = 400;
var x1 = 50;
var cy = 150;
var cx = function(d, i) {
var spacing = lineLength / data[dataset].length;
return x1 + (i * spacing);
};
var body = d3.select('body');
var svg = body.append('svg');
svg.append('text')
.attr('x', x1 + (lineLength / 2))
.attr('y', 50)
.text('data' + dataset);
svg.append('line')
.attr('x1', 0)
.attr('x2', x1 + lineLength)
.attr('y1', cy)
.attr('y2', cy);
var g = svg.append('g');
g.selectAll('circle')
.data(data[dataset])
.enter()
.append('circle')
.attr('cx', cx)
.attr('cy', cy)
.attr('r', function(d) { return d; });
body.append('button')
.text('Change data')
.on('click', function() {
dataset = Number(!dataset); // 1 <-> 0
var circles = g.selectAll('circle').data(data[dataset]);
circles.exit()
.transition()
.attr('r', 0)
.attr('cx', lineLength + x1)
.remove();
var newCircles = circles.enter().append('circle')
.attr('cx', lineLength + x1)
.attr('cy', cy)
.attr('r', 0);
newCircles.merge(circles).transition()
.duration(250)
.attr('cx', cx)
.attr('r', function(d) { return d; });
d3.select('text').text('data' + dataset);
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment