Public
Edited
Oct 27, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@7","d3-force@2", "d3-geo-projection@2")
Insert cell
data = FileAttachment("aiddata-countries-only - aiddata-countries-only.csv").csv()
Insert cell
donated = d3.rollup(
data,
group => d3.sum(group, d=> d.commitment_amount_usd_constant),
d =>d.donor
)
Insert cell
received = d3.rollup(
data,
group => d3.sum(group, d=> d.commitment_amount_usd_constant),
d =>d.recipient
)
Insert cell
Insert cell
function combineDonatedReceived(donated, received) {
const countries = new Set([...donated.keys(), ...received.keys()]);

const combinedArray = [];

for (let country of countries) {
const donatedValue = donated.get(country) || 0;
const receivedValue = received.get(country) || 0;

combinedArray.push({
country,
donated: donatedValue,
received: receivedValue
});
}

return combinedArray;
}

Insert cell
combinedDR = combineDonatedReceived(donated, received)
Insert cell
combinedDR
.sort((a,b)=>d3.descending(a.donated, b.donated))
Insert cell
maxDonated = d3.max(combinedDR, d=>d.donated)
Insert cell
maxReceived = d3.max(combinedDR, d=> d.received)
Insert cell
countries = d3.map(combinedDR, d=>d.country)
Insert cell
maxDonated>maxReceived
Insert cell
totalHeight = 1200
Insert cell
margin = ({top: 20, bottom: 45, left: 75, right: 10})
Insert cell
visWidth = width - margin.left - margin.right
Insert cell
visHeight = totalHeight - margin.top - margin.bottom
Insert cell
x = d3.scaleLinear()
.domain([0,maxReceived])
.range([0,visWidth])
Insert cell
y = d3.scaleBand()
.domain(countries)
.range([0,visHeight])
.padding(0.4)
Insert cell
function formatMillions(d) {
return `${d / 1000000} mill.`;
}
Insert cell
Insert cell
Insert cell
Insert cell
world_50 = FileAttachment("countries-50m.json").json()
Insert cell
world_50_countries = topojson.feature(world_50, world_50.objects.countries)
Insert cell
countrymesh = topojson.mesh(world_50, world_50.objects.countries, (a, b) => a !== b)
Insert cell
import {Legend} from "@d3/color-legend"
Insert cell
countries_position_50 = world_50_countries.features.filter((item) => {
return countries.includes(item.properties.name);
});
Insert cell
notMatchingCountries = countries.filter((country) => {
return !world_50_countries.features.some((item) => item.properties.name === country);
});
Insert cell
rename = new Map([
["United States of America", "United States"],
["South Korea", "Korea"],
["Czechia","Czech Republic"],
["Slovakia","Slovak Republic"]]
)
Insert cell

world_50_countries.features.forEach((item) => {
if (rename.has(item.properties.name)) {
item.properties.name = rename.get(item.properties.name);
}
});
Insert cell
notMatchingCountries_after_renamed = countries.filter((country) => {
return !world_50_countries.features.some((item) => item.properties.name === country);
});
Insert cell
Insert cell
chart_donate =()=> {

// Specify the chart’s dimensions.
const width = 928;
const marginTop = 46;
const height = width / 2 + marginTop;

// Fit the projection.
const projection = d3.geoEqualEarth().fitExtent([[2, marginTop + 2], [width - 2, height]], {type: "Sphere"});
const path = d3.geoPath(projection);

// Index the values and create the color scale.
const valuemap = new Map(combinedDR.map(d => [d.country, d.donated]));
const color = d3.scaleSequential(d3.extent(valuemap.values()), d3.interpolateYlOrRd);


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

// Reformat the money value
function formatValue(value) {
if (value >= 1000000000) {
return (value / 1000000000).toFixed(1);
} else {
return value;
}
}
// Append the legend.
svg.append("g")
.attr("transform", "translate(20,0)")
.append(() => Legend(color, {title: "Amount of Donation ( billion USD)", width: 260, tickFormat: formatValue
}))
;

// Add a steelblue sphere with a black border. (After testing, steelblue could reflect the ocean area and serve as a good backgroud color for countries' coloring )
svg.append("path")
.datum({type: "Sphere"})
.attr("fill", "steelblue")
.attr("stroke", "currentColor")
.attr("d", path);

// Add a path for each country and color it according te this data.
svg.append("g")
.selectAll("path")
.data(world_50_countries.features)
.join("path")

.attr("fill", d => {
if (valuemap.has(d.properties.name)) {
return color(valuemap.get(d.properties.name));
} else {
return "gray";
}
})
.attr("d", path)
.append("title")
.text(d => `${d.properties.name}\n${valuemap.get(d.properties.name)}`);

// Add a white mesh to draw the outline of countries on map .
svg.append("path")
.datum(countrymesh)
.attr("fill", "none")
.attr("stroke", "white")
.attr("d", path);

return svg.node();
}
Insert cell
chart_receive =()=> {

// Specify the chart’s dimensions.
const width = 928;
const marginTop = 46;
const height = width / 2 + marginTop;

// Fit the projection.
const projection = d3.geoEqualEarth().fitExtent([[2, marginTop + 2], [width - 2, height]], {type: "Sphere"});
const path = d3.geoPath(projection);

// Index the values and create the color scale.
const valuemap = new Map(combinedDR.map(d => [d.country, d.received]));
const color = d3.scaleSequential(d3.extent(valuemap.values()), d3.interpolateGnBu);


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

// Reformat the money value
function formatValue(value) {
if (value >= 1000000000) {
return (value / 1000000000).toFixed(1);
} else {
return value;
}
}
// Append the legend.
svg.append("g")
.attr("transform", "translate(20,0)")
.append(() => Legend(color, {title: "Amount of Receiving ( billion USD)", width: 260, tickFormat: formatValue
}))
;

// Add a steelblue sphere with a black border. (After testing, the steelblue here as background does not conflict with the coloring of countries' receiving amount.)
svg.append("path")
.datum({type: "Sphere"})
.attr("fill", "steelblue")
.attr("stroke", "currentColor")
.attr("d", path);

// Add a path for each country and color it according te this data.
svg.append("g")
.selectAll("path")
.data(world_50_countries.features)
.join("path")

.attr("fill", d => {
if (valuemap.has(d.properties.name)) {
return color(valuemap.get(d.properties.name));
} else {
return "gray";
}
})
.attr("d", path)
.append("title")
.text(d => `${d.properties.name}\n${valuemap.get(d.properties.name)}`);

// Add a white mesh.
svg.append("path")
.datum(countrymesh)
.attr("fill", "none")
.attr("stroke", "white")
.attr("d", path);

return svg.node();
}
Insert cell
Insert cell
{
const donate = chart_donate()
const receive = chart_receive()

return html`
<div style="display: flex">
${donate}
</div>
<div style="display: flex">

${receive}
</div>
`;

}
Insert cell
Insert cell
globalposition = FileAttachment("globalposition.json").json()
Insert cell
Insert cell
countries_position = globalposition.filter(function(item) {
return countries.includes(item.name);
});
Insert cell
Insert cell
countries_position0 = countries.filter(function(country) {
return !globalposition.some(function(item) {
return item.name === country;
});
});
Insert cell
globalposition_new = globalposition.map(function(item) {
if (rename.has(item.name)) {
item.name = rename.get(item.name);
}
return item;
});
Insert cell
all_countries_position = globalposition_new.filter(function(item) {
return countries.includes(item.name);
});
Insert cell
combinedDR1 = combinedDR
.sort((a,b)=>d3.descending(a.donated, b.donated))
Insert cell
result = all_countries_position.map(country => {
let matchingCountry = combinedDR1.find(item => item.country === country.name);
if (matchingCountry) {
return {
...country,
donated: matchingCountry.donated,
received: matchingCountry.received
};
} else {
return country;
}
});

Insert cell
Insert cell
import {slider} from "@jashkenas/inputs"
Insert cell
radius = d3.scaleSqrt([0, d3.max(result, d => d.received)], [0, k])
Insert cell
projection = d3.geoBertin1953()
Insert cell
Insert cell
simulation = d3
.forceSimulation(result)
.force("x", d3.forceX(d => projection(d.coords)[0]))
.force("y", d3.forceY(d => projection(d.coords)[1]))
.force("collide", d3.forceCollide(d => 0.5 + radius(d.donated)))
.stop()
Insert cell
path = d3.geoPath(projection)
Insert cell
world = FileAttachment("world.topojson").json()
Insert cell
map = ()=>{
// Use simulation to avoid overlapping. -- Dorling Cartogram
for (let i = 0; i < 200; i++) {
simulation.tick();
}
// Define SVG
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };

const svg = d3.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);

const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);


// Draw the globe
const sphere = ({ type: "Sphere" });
svg
.append("g")
.append("path")
.datum(sphere)
.attr("class", "graticuleOutline")
.attr("d", path)
.style('fill', "#9ACBE3");

// Draw longtitude and latitude lines
svg
.append("g")
.append("path")
.datum(d3.geoGraticule10())
.attr("class", "graticule")
.attr("d", path)
.attr("clip-path", "url(#clip)")
.style('fill', "none")
.style('stroke', "white")
.style('stroke-width', .8)
.style('stroke-opacity', .5)
.style('stroke-dasharray', 2);

// Draw countries

svg
.append("path")
.datum(topojson.feature(world, world.objects.world_countries_data))
.attr("fill", "white")
.style('fill-opacity', .5)
.attr("d", path);

// Add tooltip
const tooltip = d3.select("body")
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
.style("position", "absolute")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px");

// Reformat the money value
function formatValue(value) {
if (value >= 1000000000) {
return (value / 1000000000).toFixed(1) + " billion";
} else if (value >= 1000000) {
return (value / 1000000).toFixed(1) + " million";
} else {
return value;
}
}
// Add circles
svg
.selectAll("circle")
.data(result)
.enter()
.append("circle")
.attr("r", d => radius(d.donated))
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "#e04a28")
.attr("fill-opacity", 0.9)
.attr("stroke", "#fff")
.attr("stroke-width", 0.5)
.on("mouseover", (event, d) => {
tooltip.transition().duration(200).style("opacity", 0.9);
tooltip.html(`ID: ${d.name} <br>Donated: ${formatValue(d.donated)}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
})
.on("mouseout", () => {
tooltip.transition().duration(500).style("opacity", 0);
});

;

// Labels stored in result.id
svg
.selectAll("text")
.data(result)
.enter()
.append("text")
.attr("x", d => d.x)
.attr("y", d => d.y)
.text(d => d.id)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("font-family","sans-serif"
)
.attr("fill", "white")
.style("font-size", d => (d.donated > 2000000000 ? `${radius(d.donated) * 0.8}px` : 0));



return svg.node();
}
Insert cell
map2= ()=>{
for (let i = 0; i < 200; i++) {
simulation.tick();
}

// Define svg
const width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 80, left: 50 };

const svg = d3.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);



// Draw globe
const sphere = ({ type: "Sphere" });
svg
.append("g")
.append("path")
.datum(sphere)
.attr("class", "graticuleOutline")
.attr("d", path)
.style('fill', "#9ACBE3");

// Draw longtitude and latitude lines

svg
.append("g")
.append("path")
.datum(d3.geoGraticule10())
.attr("class", "graticule")
.attr("d", path)
.attr("clip-path", "url(#clip)")
.style('fill', "none")
.style('stroke', "white")
.style('stroke-width', .8)
.style('stroke-opacity', .5)
.style('stroke-dasharray', 2);

// Countries

svg
.append("path")
.datum(topojson.feature(world, world.objects.world_countries_data))
.attr("fill", "white")
.style('fill-opacity', .5)
.attr("d", path);

// Add tooltip
const tooltip = d3.select("body")
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
.style("position", "absolute")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px");

// Reformat the money value
function formatValue(value) {
if (value >= 1000000000) {
return (value / 1000000000).toFixed(1) + " billion";
} else if (value >= 1000000) {
return (value / 1000000).toFixed(1) + " million";
} else {
return value;
}
}

svg
.selectAll("circle")
.data(result)
.enter()
.append("circle")
.attr("r", d => radius(d.received))
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "steelblue")
.attr("fill-opacity", 0.9)
.attr("stroke", "#fff")
.attr("stroke-width", 0.5)
.on("mouseover", (event, d) => {
tooltip.transition().duration(200).style("opacity", 0.9);
tooltip.html(`ID: ${d.name} <br>Received: ${formatValue(d.received)}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
})
.on("mouseout", () => {
tooltip.transition().duration(500).style("opacity", 0);
});


// Abbreaviation of countries appears on each circle
svg
.selectAll("text")
.data(result)
.enter()
.append("text")
.attr("x", d => d.x)
.attr("y", d => d.y)
.text(d => d.id)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("font-family", "sans-serif")
.attr("fill", "white")
.style("font-size", d => (d.received > 200000000 ? `${radius(d.received) * 0.8}px` : 0));


return svg.node();
}
Insert cell
viewof k = slider({
min: 40,
max: 120,
value: 75,
step: 1,
description: "To change the size of the circles"
})
Insert cell
{
const map_1 = map()
const map_2= map2()

return html`
<div style="display: flex">
${map_1}
</div>
<div style="display: flex">

${map_2}
</div>
`;

}
Insert cell
Insert cell
Insert cell
Insert cell
top_5_donation_purposes_frequent0 = d3.rollups(
data,
group => group.length,
d => d.coalesced_purpose_name
).sort((a,b) => d3.descending(a[1],b[1]))
.slice(0,5)
Insert cell
top_5_donation_purposes_frequent = d3.rollups(
data,
group => group.length,
d => d.coalesced_purpose_name
).sort((a,b) => d3.descending(a[1],b[1]))
.slice(1,6)
Insert cell
data_filtered_frequent = data.filter(d => {
for (let i = 0; i < top_5_donation_purposes_frequent.length; i++) {
if (d.coalesced_purpose_name === top_5_donation_purposes_frequent[i][0]) {
return true;
}
}
return false;
});
Insert cell
donation_distribution_frequent = d3.groups(data_filtered_frequent, d=>d.coalesced_purpose_name)
Insert cell
result_5_frequent = {const result = {};

donation_distribution_frequent.forEach((entry) => {
let purpose = entry[0];
let data = entry[1];
if (!result[purpose]) {
result[purpose] = {};
}

data.forEach((obj) => {
let country = obj.recipient;
let amount = parseInt(obj.commitment_amount_usd_constant);

if (!result[purpose][country]) {
result[purpose][country] = 0;
}

result[purpose][country] += amount;
});
});

return result;
}

Insert cell
result_renamed_frequent = {const result_renamed = {};

for (const category in result_5_frequent) {
result_renamed[category] = {};

for (const country in result_5_frequent[category]) {
const newName = rename_v3.get(country) || country;
result_renamed[category][newName] = result_5_frequent[category][country];
}
}
return result_renamed}

Insert cell
rename_v3 = new Map([
["United States", "United States of America"],
["Korea", "South Korea"],
["Czech Republic","Czechia"],
["Slovak Republic","Slovakia"]]
)
Insert cell
Insert cell
// Find the centroid of the largest polygon
centroid = (feature) => {
const geometry = feature.geometry;
if (geometry.type === "Polygon"){
return d3.geoCentroid(feature);
}
else {
let largestPolygon = {}, largestArea = 0;
geometry.coordinates.forEach(coordinates => {
const polygon = { type: "Polygon", coordinates },
area = d3.geoArea(polygon);
if (area > largestArea) {
largestPolygon = polygon;
largestArea = area;
}
});
return d3.geoCentroid(largestPolygon);
}
}
Insert cell
world_test = {
const topo = await FileAttachment("ne_110m_admin_0_countries_lakes.json").json();
const geo = topojson.feature(topo, topo.objects.ne_110m_admin_0_countries_lakes);
geo.features.forEach(feature => {
feature.centroid = centroid(feature);
return feature;
});
return geo;
}
Insert cell
height = width * .49
Insert cell
projection_v3 = d3.geoEqualEarth()
.rotate([-10, 0, 0])
.fitSize([width, height], { type: "Sphere" });
Insert cell
patht = d3.geoPath(projection_v3);
Insert cell
max_value_v3 = d3.max(Object.values(result_5_frequent).map(obj => Object.values(obj)).flat());

Insert cell
r_v3 = d3.scaleSqrt()
.domain([0, max_value_v3])
.range([0, Math.sqrt(width * height) / 10])
Insert cell
simulation_v3 = d3.forceSimulation(world_test.features)
.force("x", d3.forceX(d => projection_v3(d.centroid)[0]))
.force("y", d3.forceY(d => projection_v3(d.centroid)[1]))
.force("collide", d3.forceCollide(d => {
if (result_5_frequent["Higher education"][d.properties.ADMIN]) {
return 1 + r_v3(result_5_frequent["Higher education"][d.properties.ADMIN]);
} else {
return 1;
}
}))
.stop();
Insert cell
colorMap_frequent = new Map([
["Social/ welfare services", "green"],
["Strengthening civil society", "orange"],
["Higher education", "steelblue"],
["Multisector aid", "red"],
["Material relief assistance and services", "purple"]
]
)
Insert cell
Insert cell
Insert cell
{
for (let i = 0; i < 200; i++){
simulation_v3.tick();
}
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("overflow", "visible");
svg.selectAll(".country")
.data(world_test.features)
.enter().append("path")
.attr("class", "country")
.attr("d", patht)
.attr("fill", "#f5f5f5")
.attr("stroke", "#e0e0e0")
.style("display", "block");

if(selections.get("Higher education")){
svg.selectAll(".circle1")
.data(world_test.features)
.enter().append("circle")
.attr("r", d => {
if (result_renamed_frequent["Higher education"] && result_renamed_frequent["Higher education"][d.properties.ADMIN]) {
return r_v3(result_renamed_frequent["Higher education"][d.properties.ADMIN]);
} else {
return 0;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "steelblue")
.attr("fill-opacity", 0.3)
.attr("stroke", "steelblue");
}


if(selections.get("Strengthening civil society")){
svg.selectAll(".circle2")
.data(world_test.features)
.enter().append("circle")
.attr("r", d => {
if (result_renamed_frequent["Strengthening civil society"] && result_renamed_frequent["Strengthening civil society"][d.properties.ADMIN]) {
return r_v3(result_renamed_frequent["Strengthening civil society"][d.properties.ADMIN]);
} else {
return 0;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "orange")
.attr("fill-opacity", 0.3)
.attr("stroke", "orange");
}
if(selections.get("Multisector aid")){
svg.selectAll(".circle3")
.data(world_test.features)
.enter().append("circle")
.attr("r", d => {
if (result_renamed_frequent["Multisector aid"] && result_renamed_frequent["Multisector aid"][d.properties.ADMIN]) {
return r_v3(result_renamed_frequent["Multisector aid"][d.properties.ADMIN]);
} else {
return 0;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "red")
.attr("fill-opacity", 0.3)
.attr("stroke", "red");

}

if(selections.get("Social/ welfare services")){
svg.selectAll(".circle4")
.data(world_test.features)
.enter().append("circle")
.attr("r", d => {
if (result_renamed_frequent["Social/ welfare services"] && result_renamed_frequent["Social/ welfare services"][d.properties.ADMIN]) {
return r_v3(result_renamed_frequent["Social/ welfare services"][d.properties.ADMIN]);
} else {
return 0;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "green")
.attr("fill-opacity", 0.3)
.attr("stroke", "green");
}


if(selections.get("Material relief assistance and services")){

svg.selectAll(".circle5")
.data(world_test.features)
.enter().append("circle")
.attr("r", d => {
if (result_renamed_frequent["Material relief assistance and services"] && result_renamed_frequent["Material relief assistance and services"][d.properties.ADMIN]) {
return r_v3(result_renamed_frequent["Material relief assistance and services"][d.properties.ADMIN]);
} else {
return 0;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", "purple")
.attr("fill-opacity", 0.3)
.attr("stroke", "purple");
}


return svg.node();
}
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