Published
Edited
Nov 19, 2020
1 star
Insert cell
md`# Members of (Croatian) Parliament by party affiliation`
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width + 60, height]);

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

svg
.append("g")
.selectAll("rect")
.data(nodes)
// .join("rect")
// .attr("x", d => d.x0 + 60)
// .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()}`);

svg
.append("g")
.attr('transform', 'translate(30,0)')
.attr("fill", "none")
.selectAll("g")
.data(links)
.join("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", d => {
console.log(d.names[0], color(d.names[0]));
return color(d.names[0]);
})
.attr("stroke-width", d => d.width)
.style("mix-blend-mode", "multiply")
.append("title")
.text(d => `${d.names.join(" → ")}\n${d.value.toLocaleString()}`);

svg
.append("g")
.style("font", "10px sans-serif")
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => (d.x0 < width / 2 ? d.x1 + 22 : d.x0 + 60))
.attr("y", d => (d.y1 + d.y0) / 2)
// .attr("dy", "0.35em")
//.attr("text-anchor", d => (d.x0 < width / 2 ? "start" : "end"))
.attr("text-anchor", "end")
.text(d => d.name)
.append("tspan")
// .append("text")
// .attr("fill-opacity", 0.7)
.attr("dx", "-20px")
.attr("dy", "1.2em")
.text(d => (d.x0 < width / 2 ? ` ${d.value.toLocaleString()}` : ''));

return svg.node();
}
Insert cell
sankey({
nodes: graph.nodes.map(d => Object.assign({}, d)),
links: graph.links.map(d => Object.assign({}, d))
})
Insert cell
color('Ostali')
Insert cell
color = d3
.scaleOrdinal(["HDZ", "SDP", "Ostali"], ["blue", "red", "lightgrey"])
.unknown("white")
Insert cell
keys = data.columns.slice(0, -1)
Insert cell
data = {
let rawData = d3.csvParse(
await FileAttachment('stranke@4.csv').text(),
d3.autoType
);

//{vote: "Remain", group: "Soft or Stay Home", value: 239}
//{stranka: "HDZ", saziv: "1990", value: 23

let retval = new Array();

let sdp = rawData.filter(
d => d.Party == 'Social Democratic Party of Croatia'
);
electionYears.forEach(year => {
retval.push({
Stranka: 'SDP',
Saziv: year.toString(),
value: sdp[0][year]
});
});

let smrtnici = rawData.filter(
d =>
d.Party != 'Croatian Democratic Union' &&
d.Party != 'Social Democratic Party of Croatia'
);

let smrtniciSum = {};
//handle all others
smrtnici.forEach(party => {
electionYears.forEach(year => {
if (smrtniciSum[year] == null) {
smrtniciSum[year] = 0;
}
smrtniciSum[year] += party[year];
});
});
electionYears.forEach(year => {
retval.push({
Stranka: 'Ostali',
Saziv: year.toString(),
value: smrtniciSum[year]
});
});

//handle HDZ:
let hdz = rawData.filter(d => d.Party == 'Croatian Democratic Union');
electionYears.forEach(year => {
retval.push({
Stranka: 'HDZ',
Saziv: year.toString(),
value: hdz[0][year]
});
});
retval.columns = ['Stranka', 'Saziv', 'value'];

return retval;
}
Insert cell
sankey = d3
.sankey()
.nodeSort(null)
.linkSort(null)
.nodeWidth(4)
.nodePadding(20)
.extent([[0, 5], [width, height - 5]])
Insert cell
height = 600
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
Insert cell
d3 = require("d3@6", "d3-sankey@0.12")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more