Public
Edited
Feb 7, 2024
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function SankeyChart({
nodes, // an iterable of node objects (typically [{id}, …]); implied by links if missing
links // an iterable of link objects (typically [{source, target}, …])
}, {
format = ",", // a function or format specifier for values in titles
nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
nodeGroup, // given d in nodes, returns an (ordinal) value for color
nodeGroups, // an array of ordinal values representing the node groups
nodeLabel, // given d in (computed) nodes, text to label the associated rect
nodeTitle = d => `${d.id}\n${format(d.value)}`, // given d in (computed) nodes, hover text
nodeAlign = d3Sankey.sankeyLeft, // Sankey node alignment strategy: left, right, justify, center
nodeWidth = _nodeWidth, // width of node rects
nodePadding = _padding, // vertical separation between adjacent nodes
nodeLabelPadding = 5, // horizontal separation between node and label
nodeStroke = "currentColor", // stroke around node rects
nodeStrokeWidth, // width of stroke around node rects, in pixels
nodeStrokeOpacity, // opacity of stroke around node rects
nodeStrokeLinejoin, // line join for stroke around node rects
linkSource = ({source}) => source, // given d in links, returns a node identifier string
linkTarget = ({target}) => target, // given d in links, returns a node identifier string
linkValue = ({value}) => value, // given d in links, returns the quantitative value
linkPath = straightLine, // given d in (computed) links, returns the SVG path # working on this
linkTitle = d => `${d.source.id} → ${d.target.id}\n${format(d.value)}`, // given d in (computed) links
linkColor = 'layered', //"#aaa", // source, target, source-target, or static color
linkStrokeOpacity = linkOpacity/100, // link stroke opacity
colors = colorScale, // array of colors
width = _width, // outer width, in pixels
height = _height, // outer height, in pixels
marginTop = 5, // top margin, in pixels
marginRight = 1, // right margin, in pixels
marginBottom = 5, // bottom margin, in pixels
marginLeft = 1, // left margin, in pixels
} = {}) {
// Compute values.
const LS = d3.map(links, linkSource).map(intern);
const LT = d3.map(links, linkTarget).map(intern);
const LV = d3.map(links, linkValue);
if (nodes === undefined) nodes = Array.from(d3.union(LS, LT), id => ({id}));
const N = d3.map(nodes, nodeId).map(intern);
const G = nodeGroup == null ? null : d3.map(nodes, nodeGroup).map(intern);
// Replace the input nodes and links with mutable objects for the simulation.
nodes = d3.map(nodes, (_, i) => ({id: N[i]}));
console.log(nodes)
links = d3.map(links, (_, i) => ({source: LS[i], target: LT[i], value: LV[i]}));

// Compute default domains.
if (G && nodeGroups === undefined) nodeGroups = G;

// Construct the scales.
const color = nodeGroup == null ? null : d3.scaleOrdinal(nodeGroups, colors);

// Compute the Sankey layout.
const sankey = d3Sankey
.sankey()
.nodeId(({index: i}) => N[i])
.nodeAlign(nodeAlign)
.nodeWidth(nodeWidth)
.nodePadding(nodePadding)
.nodeSort(null)
.iterations(_itterations)
.linkSort(linkSort)
.extent([[marginLeft, marginTop], [width - marginRight, height - marginBottom]])
({nodes, links});

// Compute titles and labels using layout nodes, so as to access aggregate values.
if (typeof format !== "function") format = d3.format(format);
const Tl = nodeLabel === undefined ? N : nodeLabel == null ? null : d3.map(nodes, nodeLabel);
const Tt = nodeTitle == null ? null : d3.map(nodes, nodeTitle);
const Lt = linkTitle == null ? null : d3.map(links, linkTitle);
console.log(nodes);
//const Vl = nodeValue === undefined ? N : nodeValue == null ? null : d3.map(nodes, nodeValue);

// A unique identifier for clip paths (to avoid conflicts).
const uid = `O-${Math.random().toString(16).slice(2)}`;

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; height: intrinsic;");

const link = svg.append("g")
.attr("fill", "none")
.selectAll("g")
.data(links)
.join("g")
.attr("stroke-opacity", d => {
if (d.value <= linkThreshold) return 0;
return linkStrokeOpacity;
})

var totalNodes = 16;
link.append("path")
.attr("d", linkPath)
.attr("stroke", function(d) {
if (linkColor === "layered") {
// Use the color of the target node for the last two nodes
if (d.target.index >= totalNodes - 2) {
return color(G[d.target.index]);
} else {
// Use the color of the source node for other nodes
return color(G[d.source.index]);
}
} else if (linkColor === "source-target") {
return `url(#${uid}-link-${d.index})`;
} else if (linkColor === "source") {
return color(G[d.source.index]);
} else if (linkColor === "target") {
return color(G[d.target.index]);
} else {
// Handle other cases or default behavior here
return linkColor;
}
})
.attr("stroke-width", ({width}) => Math.max(1, width))
.attr('stroke-linejoin', 'bevel')
.call(Lt ? path => path.append("title").text(({index: i}) => Lt[i]) : () => {});

const node = svg.append("g")
.attr("stroke", nodeStroke)
.attr("stroke-width", nodeStrokeWidth)
.attr("stroke-opacity", 1)
.attr("stroke-linejoin", nodeStrokeLinejoin)
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("x", d => d.x0)
.attr('y', d => {
if (d.id === 'Grid') return 0;
return d.y0;
})
.attr("height", d => d.y1 - d.y0,30)
.attr("width", d => d.x1 - d.x0);
if (G) node.attr("fill", ({index: i}) => color(G[i]));
if (Tt) node.append("title").text(({index: i}) => Tt[i]);
const Labels = svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => d.x0 + 34 + (d.layer * 2))
.attr("y", d => {
if (d.value <= 4) {
if (d.id === 'Solar') return d.y1 + 8;
return d.y0 - 8;
}
if (d.id === 'Grid') return (d.y1 - d.y0) / 2;
return (d.y1 + d.y0) / 2;
})
.attr('fill', d => {
if (['Nuclear', 'Hydro', 'Wind', 'Geothermal', 'Coal', 'Petroleum', 'Energy Services'].includes(d.id)) {
if (d.value > 4) return 'white';
}
return 'black';
})
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(({ index: i }) => Tl[i]);
console.log(_mode)
if (_mode === "Verbose") {
Labels.append("tspan")
.attr("x", d => d.x0 + 34 + (d.layer * 2))
.attr("y", d => {
if (d.value <= 4) {
if (d.id === 'Solar') return d.y1 + 18;
return d.y0 + 2;
}
if (d.id === 'Grid') return ((d.y1 - d.y0) / 2) + 10;
return ((d.y1 + d.y0) / 2) + 10;
})
.attr('fill', d => {
if (['Nuclear', 'Hydro', 'Wind', 'Geothermal', 'Coal', 'Petroleum', 'Energy Services'].includes(d.id)) {
if (d.value > 4) return 'white';
}
return 'black';
})
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(d => String(d.value.toFixed(2)));
}

const cloudData = [
{ x: 10, y: 40 },
{ x: 20, y: 32 },
{ x: 30, y: 40 },
{ x: 40, y: 32 },
{ x: 50, y: 40 },
{ x: 60, y: 32 },
{ x: 70, y: 40 },
{ x: 60, y: 48 },
{ x: 50, y: 56 },
{ x: 40, y: 48 },
{ x: 30, y: 56 },
{ x: 20, y: 48 },
{ x: 10, y: 56 },
];

svg.append("g")
.selectAll("circle")
.data(cloudData)
.enter()
.append("circle")
.attr("cx", d => d.x+(width*4/5))
.attr("cy", d => d.y)
.attr("r", 10)
.attr("fill", "grey")
.attr("stroke", "grey");

svg.append("text")
.attr("x", width*9/10)
.attr("y", 60)
.attr("font-size", 50)
.attr("fill","green")
.text("$");
function intern(value) {
return value !== null && typeof value === "object" ? value.valueOf() : value;
}

return Object.assign(svg.node(), {scales: {color}});
}
Insert cell
Insert cell
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