Public
Edited
Jan 26, 2024
1 star
Insert cell
Insert cell
selectedCountries = [
"DEU"
// "CHN",
// "IND",
// "USA",
// "NGA",
// "PAK",
// "COD",
// "ETH"
]
Insert cell
Plot.plot({
width: 1200,
height: 600,
inset: 10,
color: { legend: true },
x: { label: "pop", grid: true },
y: { label: "migration rate", grid: true },
marks: [
Plot.line(selection, {
x: "pop",
y: "migrationRate",
z: "location",
stroke: "location",
marker: true
}),

Plot.text(selection, {
filter: (d) => d.year % 5 === 0,
x: "pop",
y: "migrationRate",
fill: "location",
text: (d) => `${d.year}`,
dy: -8
})
]
})
Insert cell
createSegments("migrationRate")
Insert cell
createSegments("NatChangeRT")
Insert cell
/** This function generates coordinates for the lines connecting dots (for use in Datawrapper) */
createSegments = (property) => {
const groups = d3.groups(
deu.filter((d) => d.year > 1949),
(d) => d.period
);

return groups.map(([period, periodData], groupIndex) => {
return periodData.reduce((acc, cur, i) => {
const endX =
i < periodData.length - 1
? periodData[i + 1].pop
: +period < 6
? groups[groupIndex + 1][1][0].pop
: null;
const endY =
i < periodData.length - 1
? periodData[i + 1][property]
: +period < 6
? `${groups[groupIndex + 1][1][0][property]} @stroke:${
colorMatch[cur.period]
} @width:8 @opacity:0.3 @color:transparent`
: `@stroke:${
colorMatch[cur.period]
} @width:8 @opacity:0.3 @color:transparent`;

return [...acc, cur.pop, cur[property], endX, endY];
}, []);
});
}
Insert cell
data = FileAttachment("world-demographics@6.json").json()
Insert cell
untilNow = data.filter((d) => d.year <= 2023).map(d => ({...d, pop: d.pop * 1000}))
Insert cell
Insert cell
selection = untilNow.filter((d) => selectedCountries.includes(d.ISO3))
Insert cell
Insert cell
chn = untilNow
.filter((d) => d.ISO3 === "CHN")
Insert cell
chnSegments = [createSegmentsWithoutPeriod(chn, 'migrationRate')]
Insert cell
createSegmentsWithoutPeriod = (data, property) => {

return data.reduce((acc, cur, i) => {
const endX = i < data.length - 1 ? data[i + 1].pop : null;
const endY =
i < data.length - 1
? data[i + 1][property]
: `@stroke:#FF6300 @width:8 @opacity:0.3 @color:transparent`;

return [...acc, cur.pop, cur[property], endX, endY];
}, []);
}
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