Published
Edited
Sep 12, 2022
Insert cell
Insert cell
chart = {
const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));

const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(50))
.force("charge", d3.forceManyBody().strength(-600))
.force("x", d3.forceX())
.force("y", d3.forceY());
const svg = d3.create("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);
svg.call(d3.zoom()
.extent([[0, 0], [width, height]])
// .scaleExtent([1, 2])
.on("zoom", zoomed));
const g = svg.append("g");

const link = g.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.2)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", 7)
.on("mouseover", function(d) {
d3.select(this).style("stroke", "red");
})
.on("mouseout", function(d) {
d3.select(this).style("stroke", "#999");
});;

link.append("title")
//.text(d => `d.predicate +'\n' + d.sentence`);
.text(d => d.sentence);

link.on("click", function(d) {
console.log(d => d.sentence);
});
const node = g.append("g")
.attr("class", "nodes")
.selectAll("g")
.data(nodes)
.enter().append("g")
const circles = node.append("circle")
.attr("stroke", "#fff")
.attr("stroke-width", 0)
.attr("r", 10)
.attr("fill", color)
.call(drag(simulation));

node.append("text")
.text(function(d) {
return d.label;
})
.attr('font-size', 14)
.attr('x', 8)
.attr('y', 0);
node.append("title")
.text(d => d.id);

simulation.on("tick", () => {
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);

node
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
});

invalidation.then(() => simulation.stop());
//Zoom functions
function zoomed({transform}) {
g.attr("transform", transform);
}

return svg.node();
}
Insert cell
data = FileAttachment("LIPA_data.json").json()
Insert cell
height = 680
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
//const scale = d3.scaleOrdinal([`#383867`, `#584c77`, `#33431e`, `#a36629`, `#92462f`, `#b63e36`, `#b74a70`, `#946943`]); // [`#383867`, `#584c77`, `#33431e`, `#a36629`, `#92462f`, `#b63e36`, `#b74a70`, `#946943`]
return d => scale(d.group);
}
Insert cell
drag = simulation => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event,d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event,d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
d3 = require("d3@6")
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