Published
Edited
Jan 12, 2021
1 fork
2 stars
Insert cell
Insert cell
keywords="linux"
Insert cell
graph = {
const height = 600;
const root = d3.hierarchy(data);
const links = root.links();
const nodes = root.descendants();

const simulation = d3
.forceSimulation(nodes)
.force(
"link",
d3
.forceLink(links)
.id((d) => d.id)
.distance(70)
)
.force("charge", d3.forceManyBody().strength(-200))
.force(
"collide",
d3.forceCollide().radius(function (d) {
return 64;
})
)
.force("center", d3.forceCenter(width / 2, height / 2));

const svg = d3.select(DOM.svg(width, height));

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

const node = svg
.append("g")
.attr("fill", "currentColor")
.attr("stroke-linecap", "round")
.attr("stroke-linejoin", "round")
.selectAll("g")
.data(nodes)
.join("g")
.call(drag(simulation));

node
.append("circle")
.attr("stroke", "white")
.attr("stroke-width", 1.5)
.attr("r", 4);

node
.append("svg:a")
.attr("xlink:href", function (d) {
return "https://en.wikipedia.org/?curid=" + d.data.pageid;
})
.attr("target", "_blank")
.append("text")
.attr("x", 8)
.attr("y", "0.31em")
.text((d) => d.data.name)

.clone(true)
.lower()
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-width", 3);

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", (d) => `translate(${d.x},${d.y})`);
});

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

return svg.node();
}
Insert cell
wikiApiURL={
let prop2Extract = "linkshere";
return `https://cors-anywhere.sssc.workers.dev/?https://en.wikipedia.org/w/api.php?format=json&action=query&prop=${prop2Extract}&redirects=1&titles=${encodeURIComponent(
keywords
)}`;
}
Insert cell
searchResult=fetch(wikiApiURL).then(response => response.json())
Insert cell
data = Object.values(searchResult.query.pages).map((x) => {
let linkshere = x.linkshere&&x.linkshere.map((l) => {
return { name: l.title, pageid: l.pageid };
});

return { name: x.title, pageid: x.pageid, children: linkshere };
})[0];
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