Published
Edited
Dec 9, 2021
Insert cell
Insert cell
Insert cell
data = FileAttachment("GOTb3otherFamily.json").json()
Insert cell
Insert cell
chartNodes = {
// Create a copy of the node data, so we don't overwrite the original array (simulating forces will change the array)
const nodes = data.nodes.map(d => Object.create(d));

const nodesCopy = nodes;

const links = data.links.map(d => Object.create(d));
const simulation = d3.forceSimulation(nodes)
.force("center", d3.forceCenter(width/2, height/2))
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody())
;

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

// Bind the data and draw each of the nodes, note that cx and cy are all currently set to the same position
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 8)
.attr("fill", color)
.attr("cx", width/2 )
.attr("cy", height/2);

const link = svg.append("g")
.selectAll("line")
.data(links)
.join("line")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.4)


// Add the name of the character to each node, so that it is revealed on mouseover
node.append("title")
.text(d => d.name);

// TODO: Indicate how we should update the graph for each tick
simulation.on("tick", () => {
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
});

invalidation.then(() => simulation.stop());

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
height = 1000
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
return d => scale(d.group);
}
Insert cell
drag = simulation => {
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more