Public
Edited
Dec 12, 2022
1 star
Also listed in…
Forum responses
Insert cell
Insert cell
map = {
let map = d3.create("svg").attr("width", w).attr("height", h);
map
.selectAll("path")
.data(contiguous_states.features)
.join("path")
.attr("d", path)
.attr("fill", "lightgray")
.attr("stroke", "#fff")
.attr("stroke-width", 1);
map
.selectAll("circle")
.data(largest_cities)
.join("circle")
.attr("cx", (c) => c.x)
.attr("cy", (c) => c.y)
.attr("r", (c) => 5 * (c.population / largest_cities.max_pop) ** 0.3)
.attr("fill", "black")
.attr("fill-opacity", 0.5)
.attr("stroke", "black")
.attr("data-name", (c) => c.name)
.attr("data-population", (c) => c.population)
.nodes()
.forEach(function (c) {
tippy(c, {
content: `
<div>
<h3>${c.getAttribute("data-name")}</h3>
<div>Population: ${c.getAttribute("data-population")}</div>
</div>`,
theme: "light-border",
allowHTML: true
});
});

return map.node();
}
Insert cell
Insert cell
path = d3.geoPath().projection(projection)
Insert cell
projection = d3.geoAlbers().fitSize([w, h], contiguous_states)
Insert cell
h = 0.625 * w
Insert cell
w = d3.min([width, 1000])
Insert cell
Insert cell
largest_cities = {
let largest_cities = await FileAttachment("largest_cities@1.json").json();

// Here's where we use the projection to translate the lat/lon data to xy
// coordinates. We then simply attach those xy coordinates to our data.
largest_cities.forEach(function (c) {
let xy = projection(c.lonlat);
c.x = xy[0];
c.y = xy[1];
});
largest_cities.max_pop = d3.max(largest_cities.map((c) => c.population));

return largest_cities;
}
Insert cell
// The map data comes from the US Census Bureau:
// https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html
// That data was simplified a bit and converted to TopoJSON using MapShaper:
// https://mapshaper.org
contiguous_states = {
let contiguous_states = await FileAttachment(
"contiguous_states_tigerline.json"
).json();

contiguous_states = topojson.feature(
contiguous_states,
contiguous_states.objects.states
);

return contiguous_states;
}
Insert cell
Insert cell
tippy_style = html`<link style="display: none" rel="stylesheet" href="${await require.resolve(
`tippy.js/themes/light-border.css`
)}">`
Insert cell
tippy = require("tippy.js@6")
Insert cell
largest_cities
Insert cell
largest_cities.map((row) => ({
name: row.name,
population: row.population,
lat: row.lonlat[1],
lon: row.lonlat[0]
}))
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