Published
Edited
May 21, 2020
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [-width/2.5, 0, width, height]);
svg.append("g")
.attr("stroke", "#999")
.attr("stroke-width", 1.5)
.selectAll("line")
.data(data.links)
.join("line")
.attr("x1", d => d.sourceX)
.attr("y1", d => d.sourceY)
.attr("x2", d => d.targetX)
.attr("y2", d => d.targetY);
svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 4)
.selectAll("circle")
.data(data.nodes)
.join("circle")
.attr("fill", "steelblue")
.attr("r", 10)
.attr("cx", d => d.x)
.attr("cy", d => d.y);
const interval = setInterval(function() {
const updatedData = randomisePosition(data);
svg.selectAll("circle")
.data(updatedData.nodes)
.transition()
.duration(500)
.ease(d3.easeCircleOut)
.attr("cx", d => d.x)
.attr("cy", d => d.y);
svg.selectAll("line")
.data(updatedData.links)
.transition()
.duration(500)
.ease(d3.easeCircleOut)
.attr("x1", d => d.sourceX)
.attr("y1", d => d.sourceY)
.attr("x2", d => d.targetX)
.attr("y2", d => d.targetY);
}, 1000);
return svg.node();
}
Insert cell
data = {
const data = ({
nodes: nodeIds.map(d => ({id: d})),
links: [
{source: 1, target: 5},
{source: 4, target: 5},
{source: 4, target: 6},
{source: 3, target: 2},
{source: 5, target: 2},
{source: 1, target: 2},
{source: 3, target: 4}
]
})
return randomisePosition(data);
}
Insert cell
function randomisePosition(data) {
data.nodes = data.nodes.map(d => ({
id: d.id,
x: (Math.random() * 0.6 + 0.2) * height,
y: (Math.random() * 0.6 + 0.2) * height
}));
data.links = data.links.map(link => {
const source = data.nodes.filter(d => d.id === link.source)[0],
target = data.nodes.filter(d => d.id === link.target)[0];
link.sourceX = source.x;
link.sourceY = source.y;
link.targetX = target.x;
link.targetY = target.y;
return link;
});
return data;
}
Insert cell
nodeIds = d3.range(1, nNodes + 1)
Insert cell
nNodes = 6
Insert cell
height = 200
Insert cell
d3 = require("d3@5")
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