Published
Edited
Oct 14, 2020
2 forks
10 stars
Insert cell
Insert cell
chart = {
// 1. add more configurations on the simulaiton
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(edges)
.id(d => d.id)
.distance(50)
.iterations(4)
)
.force("charge", d3.forceManyBody()
.strength(-45)
)
.force("x", d3.forceX())
.force("y", d3.forceY());

const svg = d3.create("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);
// 2.1 add legend of coloring on node types
svg.append("g")
.call(legend);

const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(edges)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.value));

const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("fill", d => color(d.type))
.call(drag(simulation));

node.append("title")
.text(d => d.id + " : " + d.name);

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("cx", d => d.x)
.attr("cy", d => d.y);
});

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

return svg.node();
}
Insert cell
// 2.2 actual codes of legends
legend = svg => {
const g = svg
.attr("transform", 'translate(1200, -1200)')
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", 20)
.selectAll("g")
.data(color.domain())
.join("g")
.attr("transform", (d, i) => `translate(0,${i * 50})`);
g.append("circle")
.attr("cx", 0)
.attr("r", 20)
.attr("fill", color);

g.append("text")
.attr("x", -40)
.attr("dy", "0.4em")
.text(d => d);
}
Insert cell
edges = FileAttachment("A2K-pop_edge.csv").csv()
Insert cell
nodes = FileAttachment("A2K-pop_node.csv").csv()
Insert cell
height = 3000
Insert cell
width = height
Insert cell
color = d3.scaleOrdinal(["male", "female", "person","group","label"], ["#4e79a7","#e15759","#edc949","#f28e2c","#000000"])
// 2.3 color the nodes according to different groups
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
import {serialize} from "@mbostock/saving-svg"
Insert cell
DOM.download(() => serialize(chart), undefined, "Save as SVG")
Insert cell
import {swatches} from "@d3/color-legend"
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