Public
Edited
Oct 25, 2023
1 fork
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
combinedDR1 = 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
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
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
rename = new Map([
["United States of America", "United States"],
["South Korea", "Korea"],
["Czechia","Czech Republic"],
["Slovakia","Slovak Republic"]]
)
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
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
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 ages = map()
const barchart_gender = map2()

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

${barchart_gender}
</div>
`;

}
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