Published
Edited
Jul 20, 2022
Fork of Bubble Map
2 forks
1 star
Also listed in…
Forum responses
Insert cell
Insert cell
Insert cell
Insert cell
map = {
// We're going to draw the map on the following SVG.
let svg = d3.create("svg").attr("width", w).attr("height", h);

// Draw the graticule
svg
.append("path")
.attr("d", path(d3.geoGraticule10()))
.attr("fill", "none")
.attr("stroke", "#333")
.attr("stroke-width", 0.4);

// Draw the countries
let country_group = svg.append("g");
country_group
.selectAll("path")
.data(countries.features)
.join("path")
.attr("d", path)
.attr("fill", "#eee")
.attr("stroke", "black")
.attr("stroke-width", 1);

// Compute the centroids and associate those results with a country identifier
let centroid_map = new Map();
countries.features.forEach(function (c) {
let centroid = path.centroid(c);
if (!isNaN(centroid[0])) {
centroid_map.set(c.properties.NAME, centroid);
}
});

// The names of the countries in one file don't necessarily agree with
// the names in the other. You can manually set the centroid for a
// name in the CSV file to the value in the GEO file as follows:
centroid_map.set(
"United States",
centroid_map.get("United States of America")
);
centroid_map.set("Cote d Ivorie", centroid_map.get("Côte d'Ivoire"));

// Draw the bubbles.
let p = parameter.toLowerCase().replace(" ", "_");
let max = d3.max(country_data.map((o) => +o[p]));
let bubble_group = svg.append("g");
bubble_group
.selectAll("circle")
.data(country_data.filter((o) => centroid_map.has(o.CountryName)))
.join("circle")
.attr("cx", (d) => centroid_map.get(d.CountryName)[0])
.attr("cy", (d) => centroid_map.get(d.CountryName)[1])
.attr("r", (d) => 20 * Math.sqrt(+d[p] / max))
.attr("fill", "lightblue")
.attr("stroke", "black");

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
path = d3.geoPath().projection(projection)
Insert cell
projection = d3.geoNaturalEarth1().fitSize([w + 20, h], countries)
Insert cell
h = 0.625 * w
Insert cell
w = width < 1200 ? width : 1200
Insert cell
// Convert the TopoJSON to GeoJSON
countries = topojson.feature(map_data, map_data.objects.countries)
Insert cell
map_data = FileAttachment("countries@1.json").json()
Insert cell
country_data = d3.csvParse(await fetch("https://raw.githubusercontent.com/SandeshDhungel/datadoc/main/countries.csv").then(d => d.text()))
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