Skip to content

Instantly share code, notes, and snippets.

@cramja
Last active Apr 6, 2017
Embed
What would you like to do?
Example of updates with merging in d3
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
circle {
fill:red;
stroke: black;
stroke-width:2px;
}
.my_circ {
fill: blue;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var alphabet = "thequickbrownfoxjumpsoverthelazydog".split("");
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(32," + (height / 2) + ")"),
g_circ = svg.append("g").attr("transform", "translate(32," + (height / 2 + 32) + ")");
var num_update = 0;
var mycirc = svg.append("circle")
.attr("r", 20)
.attr("cx", 50)
.attr("cy", 50);
function update(data) {
num_update+=1;
var circs = g_circ.selectAll("circle")
.data(data);
circs.enter()
.append("circle")
.attr("r", 10)
.attr("cx", function(d, i) { return i * 32 + 10; })
.attr("cy", 10)
.merge(circs).classed("my_circ", function(d, i) {
return ((i + num_update) % 2) == true;
});
circs.exit().remove();
// var mycirc = svg.selectAll("circle")
// .classed("my_circ", (num_update % 2) == true);
// DATA JOIN
// Join new data with old elements, if any.
var text = g.selectAll("text")
.data(data);
// UPDATE
// Update old elements as needed.
text.attr("class", "update");
// ENTER
// Create new elements as needed.
//
// ENTER + UPDATE
// After merging the entered elements with the update selection,
// apply operations to both.
text.enter().append("text")
.attr("class", "enter")
.attr("x", function(d, i) { return i * 32; })
.attr("dy", ".35em")
.merge(text)
.text(function(d) { return d; });
// EXIT
// Remove old elements as needed.
text.exit().remove();
}
// The initial display.
update(alphabet);
// Grab a random sample of letters from the alphabet, in alphabetical order.
d3.interval(function() {
update(d3.shuffle(alphabet)
.slice(0, Math.floor(Math.random() * alphabet.length))
.sort());
}, 1500);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment