Published
Edited
Aug 23, 2020
2 forks
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", "-" + adj + " -"+ adj + " " + (width + adj*2) + " " + (height + adj*2))
.style("background", mode === "dark" ? "#2e2e2e" : "#fff");

const {nodes, links} = sankey({
nodes: graph.nodes.map(d => Object.assign({}, d)),
links: graph.links.map(d => Object.assign({}, d))
});

//adding nodes
svg.append("g")
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("height", d => d.y1 - d.y0)
.attr("width", d => d.x1 - d.x0)
.append("title")
.text(d => `${d.name}\n${d.value.toLocaleString()}`);

//adding path links connecting nodes. Remove mouseover event if you want highlight to work only when the user hovers on the labels of the first series
const path = svg.append("g")
.attr("fill", "none")
.selectAll("g")
.data(links)
.join("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", mode === "dark" ? single_color_dark_mode : single_color)
.attr("stroke-width", d => d.width)
.style("mix-blend-mode", mode === "dark" ? "lighten" : "multiply")
.on("mouseover", d => {
console.log(d);
path.attr("stroke", l => {
console.log(l);
if(l.names[0]===d.names[0]){return color(d.names[0]);}
else {
return mode === "dark" ? single_color_dark_mode : single_color;
}
});
})
.on("mouseout", d => {
path.attr("stroke", mode === "dark" ? single_color_dark_mode : single_color);
});
path.append("title")
.text(d => `${d.names.join(" → ")}\n${d.value.toLocaleString()}`);

//adding title labels
const label = svg.append("g")
.style("font", "10px sans-serif")
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
.text(d => d.name)
.attr("fill", mode==="dark" ? "#f2e8d2" : "#000")
.append("tspan")
.attr("fill-opacity", 0.7)
.text(d => ` ${d.value.toLocaleString()}`);
/* enable if you want hover to work ONLY when the user hovers on the labels of the first series
svg.append("g")
.attr("fill", "none")
.attr("pointer-events", "all")
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("width", 50)
.attr("height", 10)
.attr("x", d => (d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6))
.attr("y", d => ((d.y1 + d.y0) / 2)-6)
.attr("dy", "0.35em")
.on("mouseover", d => {
path.attr("stroke",l => {
if(l.names[0]==d.name){return color(d.name);}
else {return single_color;}
});
})
.on("mouseout", d => {
path.attr("stroke", single_color);
});
*/

return svg.node();
}
Insert cell
mode = Generators.observe(notify => {
const query = matchMedia("(prefers-color-scheme: dark)");
const changed = () => notify(query.matches ? "dark" : "light");
changed();
query.addListener(changed);
return () => query.removeListener(changed);
})
Insert cell
adj = 50
Insert cell
width = 970 - adj*2
Insert cell
height = 720 - adj*2
Insert cell
single_color = "#eee"
Insert cell
single_color_dark_mode = "#3f3f3f"
Insert cell
sankey = d3.sankey()
.nodeSort(null)//null and undefined are two options here
.linkSort(null)//null and undefined are two options here
.nodeWidth(4)
.nodePadding(27)//space between two nodes
.extent([[0, 5], [width, height - 5]])
Insert cell
graph = {
let index = -1;
const nodes = [];
const nodeByKey = new Map;
const indexByKey = new Map;
const links = [];

for (const k of keys) {
for (const d of data) {
const key = JSON.stringify([k, d[k]]);
if (nodeByKey.has(key)) continue;
const node = {name: d[k]};
nodes.push(node);
nodeByKey.set(key, node);
indexByKey.set(key, ++index);
}
}

for (let i = 1; i < keys.length; ++i) {
const a = keys[i - 1];
const b = keys[i];
const prefix = keys.slice(0, i + 1);
const linkByKey = new Map;
for (const d of data) {
const names = prefix.map(k => d[k]);
const key = JSON.stringify(names);
const value = d.value || 1;
let link = linkByKey.get(key);
if (link) { link.value += value; continue; }
link = {
source: indexByKey.get(JSON.stringify([a, d[a]])),
target: indexByKey.get(JSON.stringify([b, d[b]])),
names,
value
};
links.push(link);
linkByKey.set(key, link);
}
}

return {nodes, links};
}
Insert cell
color = d3.scaleOrdinal(["Perished","Survived"], ["#da4f81","#488f31"]).unknown("#ccc")
Insert cell
keys = data.columns.slice(0, -1)
Insert cell
data = d3.csvParse(await FileAttachment("titanic.csv").text(), d3.autoType)
Insert cell
d3 = require("d3@5", "d3-sankey@0.12")
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