Published
Edited
Jan 19, 2022
2 stars
Insert cell
Insert cell
Insert cell
data = Array(Math.ceil(Math.random() * 6))
.fill()
.map((d) => [Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6)])
Insert cell
graph = {
const sel = d3.create("svg");
const teams = sel
.selectAll("text")
.data(data)
.join((enter) =>
enter
.append("text")
.attr("transform", (d) => `translate(0, ${d[1] * 10})`)
.text((d) => d[0])
)
.transition()
.delay(500)
.attr("transform", (d) => `translate(0, ${d[1] * 30})`);
return sel.node();
}
Insert cell
Insert cell
data2 = {
while (true) {
yield Array(Math.ceil(Math.random() * 6))
.fill()
.map((d) => [Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6)]);
await Promises.delay(2000);
}
}
Insert cell
// This cell does not re-run when data2 changes
graph2 = {
// At first, just create the basic SVG
const sel = d3.create("svg");

// Return the SVG node and attach an update method
return Object.assign(sel.node(), {
update: (data) => {
// Run the join code with the data passed to the update method
const teams = sel
.selectAll("text")
.data(data)
.join(
(enter) =>
// New items fade in from the left
enter
.append("text")
.attr("opacity", 0)
.text((d) => d[0])
.attr("transform", (d) => `translate(-50, ${d[1] * 10})`)
.transition()
.attr("transform", (d) => `translate(0, ${d[1] * 10})`)
.attr("opacity", 1),
// Existing items update their text and transition to their new vertical position
(update) =>
update
.text(d => d[0])
.transition()
.attr("transform", (d) => `translate(0, ${d[1] * 10})`),
// Removed items fade out to the right
(exit) =>
exit
.transition()
.attr("transform", (d) => `translate(50, ${d[1] * 10})`)
.attr("opacity", 0)
.remove()
);
}
});
}
Insert cell
// This cell re-runs each time data2 changes; it passes data2 to graph2’s update method, which runs the join code without destroying and recreating all of graphic2.
graph2.update(data2)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more