Published
Edited
Jul 21, 2020
Importers
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
forceGraphDemoWithAdj = forceGraph(demoData, { height: 340, chargeStrength: (d) => -240, linkDistance: (d) => 80, nodeRadius: (d) => 10, fontStyle: "28px JetBrains Mono, monospace" })
Insert cell
forceGraphDemo = forceGraph(demoData, { height: 340 })
Insert cell
forceGraph = {
return (data, {
groups = distinct(data.nodes.map(({ group }) => group)),
linkTypes = distinct(data.links.map(({ type }) => type)),
height = 680,
scale = d3.scaleOrdinal(groups, d3.schemeCategory10),
color = d => scale(d.group),
linkTypesToLabel = [],
nodeGroupsToLabel = [],
nodeRadius = (d) => 5,
linkDistance = (d) => 40,
chargeStrength = (d) => -120,
fontStyle = "12px sans-serif",
} = {}) => {
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(linkDistance))
.force("charge", d3.forceManyBody().strength(chargeStrength))
.force("collision", d3.forceCollide().radius(nodeRadius))
.force("x", d3.forceX())
.force("y", d3.forceY());

const svg = d3.create("svg")
.style("font", fontStyle)
.attr("viewBox", [-width / 2, -height / 2, width, height]);
// Link arrows
svg.append("defs").selectAll("marker")
.data(["arrow"])
.enter()
.append("marker")
.attr("id", d => d)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -0.5)
.attr("markerWidth", 3)
.attr("markerHeight", 3)
.attr("orient", "auto")
.append("path")
.attr("fill", "#999")
.attr("d", "M0,-5L10,0L0,5");
// root svg element, which makes global scaling/ transformations easier
const root = svg.append("g");
const link = root.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.value) * 2)
.attr("marker-end", d => `url(#arrow)`);
// for link hovering
link.append("title").text(d => d.type);
// optional labels
const linkLabels = root
.selectAll(".link-label")
.data(links.filter(l => linkTypesToLabel.includes(l.type)))
.enter()
.append('text')
.attr("class", "link-label label")
.attr("text-anchor", "middle")
.text(d => d.type);
const node = root.append("g")
.attr("stroke-width", 1.5)
.attr("stroke-linecap", "round")
.attr("stroke-linejoin", "round")
.selectAll("g")
.data(nodes)
.join("g")
.attr("class", d => nodeGroupsToLabel.includes(d.group) ? "node show-label" : "node")
.call(stickyDrag(simulation));

// Node circles
const nodeCircle = node.append("circle")
.attr("r", nodeRadius)
.attr("stroke", "#fff")
.attr("fill", color)
.on("dblclick", function(d) {
// unfix the node
d3.select(this.parentNode).classed("fixed", false);
d.fx = null;
d.fy = null;
})
.on("click", function(d, i, arr) {
if (d3.event.defaultPrevented) return; // dragged or double-clicked
toggleClass(d3.select(this.parentNode), "show-label");
});
// add text for hover
nodeCircle.append("title")
.text(({ group, name }) => `${group}: ${name}`);

// optional text labels with white border
node.append("text")
.attr("x", d => -(d.name.length * 2))
.attr("y", "-0.5em")
.attr("fill", "black")
.text(({ name }) => name)
.clone(true)
.lower()
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-width", 3);
// force simulation, update link, nodes, and labels
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);

linkLabels
.attr("x", d => ((d.source.x + d.target.x) / 2))
.attr("y", d => ((d.source.y + d.target.y) / 2));
node.attr("transform", d => `translate(${d.x},${d.y})`);
});
invalidation.then(() => simulation.stop());

const zoom = d3.zoom();
zoom.on("zoom", () => {
const { transform } = d3.event;
root.attr("transform", transform);
});
svg.call(zoom)
.call(zoom.transform, d3.zoomIdentity)
.on("dblclick.zoom", null); // used for resetting nodes
const reset = () => {
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}
function toggleClass(selection, className) {
selection.classed(className, !selection.classed(className));
}
return Object.assign(svg.node(), {
reset,
scale: scale,
color: color,
});
}
}
Insert cell
forceGraphStyles = css('Force Graph Styles')`

svg {
cursor: grab;
}

.node {
cursor: pointer;
}

.node > text {
visibility: hidden;
}

.node.show-label > text {
visibility: visible;
}

.node.fixed > circle {
stroke: black;
}

`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@5")
Insert cell
import { css, collapsedCSS } from "@j-f1/css-template-tag"
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