Skip to main content

Population Density Map

What is a population density map?​

A population density map is a map of how many people live on each unit of land, such as people per square mile or per square kilometre, across a region. It is usually drawn as a choropleth, with areas shaded by density, as a dot density map, with one dot per set number of people, or in 3D, with heights.

A choropleth map of the 3,108 counties of the contiguous United States, shaded by 2020 population density in five classes from under 10 to over 1,000 people per square mile. The densest counties form a band from Boston to Washington, and cluster around cities such as Chicago, Atlanta, Los Angeles and San Francisco, while many counties in the Great Plains and the West have under 10 people per square mile

Population density of every county in the contiguous United States, 2020 Census. Try the interactive version, and switch it to a dot density map.

Key takeaways
  • Population density is people divided by land area. A density map shows where people are packed closely, not how many live in each area.
  • A choropleth is best for reading and comparing each area's density. A dot density map shows where the people are, but the dots are placed at random inside each area.
  • A 3D map shows concentration at a glance, but hides columns behind columns and makes heights hard to compare.
  • Big, empty areas fill much of a US county map: counties under 10 people per square mile cover 36.5% of the land but hold 1.2% of the people.

How to read a population density map​

A density figure is a count divided by an area. The diagram below follows one county through that sum and then onto the three kinds of map on this page.

Kershaw County, South Carolina, mapped three ways. First, its 65,403 people divided by 726.6 square miles of land gives 90 people per square mile. Second, a choropleth shades the whole county in the colour of the 50 to 250 class. Third, a dot density map with one dot per 1,000 people puts 65 dots at random places inside the county. Fourth, a 3D map raises the county as a block whose height stands for 90 people per square mile

To read a population density map:

  1. Check the unit and the year. People per square mile and people per square kilometre differ by a factor of 2.59, so 90 per square mile is about 35 per square kilometre.
  2. Check what the areas are. A map of states, counties, census tracts or grid squares gives one figure per area. The smaller the areas, the more detail you see.
  3. Read the legend. Across the counties of the contiguous US they run from 0.1 to almost 75,000 people per square mile. The class breaks often grow by a multiple, such as 10, 50, 250 and 1,000, rather than in equal steps.
  4. Look for patterns: dense clusters (cities), lines of dense areas along coasts, rivers and roads, and large empty regions.
  5. Remember that each colour, column or patch of dots is an average for its whole area. A county of 90 people per square mile can hold a town of thousands and miles of empty forest.

Choropleth, dot density or 3D: three maps of the same data​

All three maps on this page use the same data: the 2020 Census population and land area of each of the 3,108 counties and county-equivalents in the 48 contiguous states and the District of Columbia. Together they had 329,260,619 people on 2,955,593 square miles of land, an average of 111.4 people per square mile. Alaska and Hawaii are left out to keep the map at one scale.

MapHow it shows densityGood forWatch out for
Choropleth mapEach county shaded by its people per square mileReading and comparing the density of each area, ranking areasLarge, sparse counties fill most of the picture; small, dense ones are specks
Dot density mapOne dot per 200, 1,000 or 5,000 people, placed inside each countySeeing where the people are, and the total in a regionDots spread evenly over each county, wherever people actually live
3D column mapEach 40 km square raised to a height set by its densityShowing how concentrated people are in a few placesColumns hide each other, and heights are hard to compare

The choropleth and the dot density map can give opposite impressions of the same country. On the choropleth, counties with under 10 people per square mile are the largest colour on the map: 556 counties covering 36.5% of the land. Yet they hold only 1.2% of the population. The 153 counties with 1,000 or more people per square mile cover 2.1% of the land and hold 40.1% of the people. Half of the population of the contiguous United States lives in the 233 densest counties, on 3.6% of its land.

A dot density map shows those 40% as dense crowds of dots on a small part of the map, and the 3D map shows them as a few tall columns.

What is a dot density map?​

A dot density map (also called a dot distribution map or dot map) shows a count with dots of one size, each standing for a fixed number, such as 1 dot = 1,000 people, placed inside the area the count belongs to. Density shows as how tightly the dots are packed.

A dot density map is drawn from counts, so you don't divide by the area first as you would for a choropleth. A big county and a small one with the same population get the same number of dots, and the small one looks denser because its dots are closer together.

For how to choose the dot value and dot size, where to place the dots, and how to map two categories in two colours, see the dot density map guide.

Dot value and dot size​

The dot value is the number each dot stands for. It decides how the map looks:

Dot valueDots for the contiguous USWhat happens
1 dot = 200 people1,646,324Detail in sparse areas; dense areas merge into solid colour unless the dots are see-through
1 dot = 1,000 people329,283A balance at the scale of the whole country; 7 counties get no dot
1 dot = 5,000 people65,836Clear, separate dots; 137 counties with under 2,500 people get no dot at all

Each county's dot count is its population divided by the dot value, rounded, so small counties drop off the map as the dot value grows. Pick the dot value and dot size together: in the densest areas, dots should just start to touch. Dots that merge hide the differences between dense places, and too few dots make thinly settled regions look empty.

Why the dots aren't where people live​

The data gives one number per county, not the address of each person, so the dots are placed at random inside each county. That works for small counties and misleads in big ones. San Bernardino County, California, has 2,181,654 people on 20,068 square miles, much of it in the Mojave Desert. A dot density map spreads its dots evenly across the whole county, but the Census Bureau puts the county's centre of population about 45 km from its western edge and 70 km from its southern edge, in a county over 300 km wide.

Two fixes are common:

  • Use smaller areas, such as census tracts or blocks, so each dot has less room to stray.
  • Use dasymetric mapping: place the dots, or the people, only on land that is likely to be lived on, using land cover or building data, and leave out water, parks and desert.

3D population density maps: what height shows and hides​

A 3D map raises each area to a height set by its density, so a column 10 times as tall stands for 10 times as many people per square mile. Below, the contiguous United States is cut into 40 km squares. The map uses an equal-area projection, so every square covers the same ground and every column has the same footprint: only the height changes. Columns standing on counties would have footprints of very different sizes. Each square's density is the average of the counties covering it, so people are again assumed to be spread evenly within each county.

Drag to rotate the map, scroll to zoom, and double-click to reset the view. Hover over a column to see its density and its rank.

In the 3D view the big cities stand out at once. The square over New York City and the neighbouring part of New Jersey averages 17,162 people per square mile, twice the next-tallest (8,266, over Queens and Nassau County), while the median square has 27. Of the 5,061 squares, 122 have 1,000 or more people per square mile, and 1,595 have fewer than 10.

The 3D view also hides things:

  • Tall columns block the ones behind them, so what you see depends on where you look from.
  • Perspective makes far columns look shorter than near ones of the same height.
  • In experiments on reading charts, people judged positions along a common scale more accurately than lengths. On a map, columns stand at different places and distances, so they never line up against a common baseline.
  • With heights in proportion to density, a few cities dwarf everything else, and most of the country stays flat.

Use 3D to show concentration, and keep a way to read exact values: tooltips, a top-down view, or a 2D map beside it.

When to use a population density map​

Use a population density map when the question is where people live closely together and where they don't: planning services, siting shops or transport, studying cities and suburbs, or putting other rates, such as disease or crime, in context. Pick the kind of map by what readers need to do.

ChartBest for
Choropleth population density mapReading the density of each area, and comparing areas against a legend
Dot density mapShowing where the people are and how many, with one dot per fixed number
3D column or prism mapShowing how concentrated people are in a few places, for an overview
Proportional symbol mapTotal population of cities or areas: a circle sized by the count, like a bubble chart on a map
Grid or heatmapDensity on equal squares or hexagons, so area sizes don't distort the picture
Bar chartRanking areas by density exactly, when location doesn't matter

For the general rules of shading areas by a value, such as normalising and choosing class breaks, see the choropleth map guide.

Common population density map mistakes​

  • Shading by population instead of density. A choropleth of total population mostly shows which areas are big or populous. Divide by land area first.
  • Dividing by total area. Lakes, bays and the sea inflate the area and lower the density. Census figures use land area.
  • Comparing maps drawn on different areas. The size of the areas changes the figures. In 2020 the District of Columbia, the densest of the 50 states and DC, had 11,280 people per square mile; New York County, the densest county, had 74,781, more than six times as many. Compare maps only when they use the same kind of area.
  • A distorting projection. Web Mercator, the projection of most web map tiles, enlarges areas far from the equator, so northern regions look bigger and emptier. Density maps belong on an equal-area projection.
  • Reading dots as addresses. On most dot density maps, each dot's position inside its area is random. Say so in the legend or caption.
  • 3D with no way to read values. Add tooltips or a top-down view, and don't ask readers to compare columns by eye.

How to create a population density map in JavaScript, React or Angular​

SciChart.js draws charts with WebGL, so a map of 3,108 county outlines, or 1.6 million dots, stays smooth to zoom and pan. The demo below draws the counties with triangle series, one per density class, the dots with a single scatter series, and the 3D view with a 3D column series.

Choose Choropleth, Dot density or 3D with the buttons; in the dot view, choose how many people each dot stands for. Hover over a county to see its name, density, population and land area. Scroll to zoom into a city, drag to pan, and double-click to reset. The 3D view is the column map from the section above, in the same demo.

Here is the code for this population density map. Each county arrives with its name, population, land area in square miles and outline, which the demo decodes into rings of [x, y] points in kilometres:

{
"name": "Kershaw",
"state": "SC",
"population": 65403,
"landArea": 726.6,
"rings": [[[1373, 1376], [1383, 1387], …, [1384, 1368]]]
}
// Create a JavaScript population density map with SciChart.js: every county in the contiguous United States,
// shown as a choropleth (one colour per county) or as a dot density map (one dot per 200, 1,000 or 5,000 people)
// (the 3D view, density as columns, is populationDensity3D() further down)
const {
SciChartSurface,
NumericAxis,
NumberRange,
XyDataSeries,
FastTriangleRenderableSeries,
ETriangleSeriesDrawMode,
FastLineRenderableSeries,
XyScatterRenderableSeries,
SquarePointMarker,
BoxAnnotation,
NativeTextAnnotation,
ECoordinateMode,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
EMultiLineAlignment,
Thickness,
CustomChartModifier2D,
translateFromCanvasToSeriesViewRect,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme,
SciChart3DSurface,
NumericAxis3D,
Vector3,
XyzDataSeries3D,
ColumnRenderableSeries3D,
CubePointMarker3D,
PointLineRenderableSeries3D,
OrbitModifier3D,
MouseWheelZoomModifier3D,
ResetCamera3DModifier,
TooltipModifier3D,
parseColorToUIntArgb
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// Dot values to choose from. With fewer, bigger dots, each dot needs more ink to stay visible;
// with millions of small dots, see-through dots stop dense areas turning into one solid blob.
const DOT_STYLES = [
{ peoplePerDot: 200, fill: "#FFD16618", size: 1 },
{ peoplePerDot: 1000, fill: "#FFD16660", size: 1 },
{ peoplePerDot: 5000, fill: "#FFD166", size: 2 }
];

// Choropleth classes in people per square mile. County densities run from under 1 to over 70,000,
// so the breaks grow about five times from one class to the next. Brighter means denser on a dark background.
const DENSITY_CLASSES = [
{ label: "Under 10", max: 10, color: "#46327E" },
{ label: "10 to 50", max: 50, color: "#365C8D" },
{ label: "50 to 250", max: 250, color: "#1F9A8A" },
{ label: "250 to 1,000", max: 1000, color: "#6CCE59" },
{ label: "1,000 and over", max: Infinity, color: "#FDE725" }
];

function getClassIndex(density) {
return DENSITY_CLASSES.findIndex((densityClass) => density < densityClass.max);
}

// 1. DATA HELPERS (plain JavaScript, no SciChart code)

// Decode one outline from the encoded polyline format (the same idea as Google's polyline encoding):
// each number is the change from the previous point in whole kilometres, written in 5-bit chunks as characters.
function decodeOutline(encoded) {
const points = [];
let index = 0;
let x = 0;
let y = 0;
const nextNumber = () => {
let result = 0;
let shift = 0;
let chunk;
do {
chunk = encoded.charCodeAt(index++) - 63;
result |= (chunk & 0x1f) << shift;
shift += 5;
} while (chunk >= 0x20);
return result & 1 ? ~(result >> 1) : result >> 1;
};
while (index < encoded.length) {
x += nextNumber();
y += nextNumber();
points.push([x, y]);
}
return points;
}

// The triangle series draws triangles, not polygons, so each outline is cut into triangles by ear clipping:
// repeatedly cut off a corner ("ear") that has no other point inside it.
// For large or complex maps, use a tested library such as earcut, or triangulate once offline.
function triangulateRing(ring) {
const points = ring.slice();
let signedArea = 0;
points.forEach(([x1, y1], i) => {
const [x2, y2] = points[(i + 1) % points.length];
signedArea += x1 * y2 - x2 * y1;
});
if (signedArea < 0) points.reverse(); // make the ring counter-clockwise

const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const isInside = (p, a, b, c) => cross(a, b, p) >= 0 && cross(b, c, p) >= 0 && cross(c, a, p) >= 0;

const remaining = points;
const triangles = []; // flat list: every three points make one triangle
while (remaining.length > 3) {
const n = remaining.length;
let earIndex = -1;
for (let i = 0; i < n && earIndex < 0; i++) {
const a = remaining[(i + n - 1) % n];
const b = remaining[i];
const c = remaining[(i + 1) % n];
if (cross(a, b, c) <= 0) continue; // not a convex corner
const blocked = remaining.some(
(p) => p !== a && p !== b && p !== c && !(p[0] === b[0] && p[1] === b[1]) && isInside(p, a, b, c)
);
if (!blocked) {
triangles.push(a, b, c);
earIndex = i;
}
}
if (earIndex < 0) {
// No ear found: drop a point that lies on a straight line, or stop
earIndex = remaining.findIndex((b, i) => cross(remaining[(i + n - 1) % n], b, remaining[(i + 1) % n]) === 0);
if (earIndex < 0) break;
}
remaining.splice(earIndex, 1);
}
if (remaining.length === 3) triangles.push(...remaining);
return triangles;
}

// Is the point inside the ring? (ray casting: count how many edges a horizontal line from the point crosses)
function isPointInRing(x, y, ring) {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i];
const [xj, yj] = ring[j];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}

// Flatten rings into x and y arrays with NaN between rings, so one line series draws them all with gaps
function ringsToLine(rings, closeRings) {
const xValues = [];
const yValues = [];
rings.forEach((ring) => {
ring.forEach(([x, y]) => {
xValues.push(x);
yValues.push(y);
});
if (closeRings) {
xValues.push(ring[0][0]);
yValues.push(ring[0][1]);
}
xValues.push(NaN);
yValues.push(NaN);
});
return { xValues, yValues };
}

// A seeded random number generator, so the dots land in the same places every time
function createRandom(seed) {
return () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
}

// 2. DOT DENSITY: county.dotCount dots per county, each at a random place inside the county.
// A triangle is picked with a chance in proportion to its area, then a random point inside it,
// so the dots are spread evenly over the county.
function placeDots(counties, random) {
const total = counties.reduce((sum, county) => sum + county.dotCount, 0);
const xValues = new Float64Array(total);
const yValues = new Float64Array(total);
let next = 0;
counties.forEach((county) => {
const { triangles, cumulativeAreas } = county;
const totalArea = cumulativeAreas[cumulativeAreas.length - 1];
for (let d = 0; d < county.dotCount; d++) {
// Binary search for the triangle that holds this share of the area
const target = random() * totalArea;
let low = 0;
let high = cumulativeAreas.length - 1;
while (low < high) {
const mid = (low + high) >> 1;
if (cumulativeAreas[mid] < target) low = mid + 1;
else high = mid;
}
const [a, b, c] = [triangles[low * 3], triangles[low * 3 + 1], triangles[low * 3 + 2]];
// A uniform random point in the triangle: fold points from the far half back in
let u = random();
let v = random();
if (u + v > 1) {
u = 1 - u;
v = 1 - v;
}
xValues[next] = a[0] + u * (b[0] - a[0]) + v * (c[0] - a[0]);
yValues[next] = a[1] + u * (b[1] - a[1]) + v * (c[1] - a[1]);
next++;
}
});
return { xValues, yValues, total };
}

// 3. HOVER TOOLTIP: finds the county under the mouse and shows its name and figures
class CountyTooltipModifier extends CustomChartModifier2D {
counties;
highlight;
tooltip;
hoveredCounty;

constructor(counties, highlight) {
super();
this.counties = counties;
this.highlight = highlight;
this.tooltip = new NativeTextAnnotation({
text: "",
isHidden: true,
textColor: "#FFFFFF",
fontSize: 15,
background: "#0F1A2B",
multiLineAlignment: EMultiLineAlignment.Left,
padding: new Thickness(6, 10, 6, 10),
lineSpacing: 4,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom
});
}

onAttach() {
super.onAttach();
this.parentSurface.annotations.add(this.tooltip);
}

onDetach() {
this.parentSurface?.annotations.remove(this.tooltip);
super.onDetach();
}

// The smallest county that contains the point: a few independent cities sit inside a county.
// This checks every county on each mouse move. The bounding-box test rules most of them out cheaply,
// which is fast enough for about 3,000 counties. For much more data, such as 85,000 census tracts:
// - Build a spatial index once: cut the map into a grid of cells (say 50 km) and list, for each cell,
// the areas whose bounding box overlaps it. On mouse move, look up the one cell under the mouse
// and test only its areas, a handful instead of thousands. A library such as rbush (an R-tree) does the same job.
// - Skip the search when the mouse is still inside the last area found.
// - Or use a hit-test bitmap: draw each area offscreen in a unique colour, and read the colour under the mouse.
findCounty(x, y) {
let found;
for (const county of this.counties) {
const { minX, maxX, minY, maxY } = county.bounds;
if (x < minX || x > maxX || y < minY || y > maxY) continue;
if (!county.rings.some((ring) => isPointInRing(x, y, ring))) continue;
if (!found || county.landArea < found.landArea) found = county;
}
return found;
}

modifierMouseMove(args) {
super.modifierMouseMove(args);
const point = translateFromCanvasToSeriesViewRect(args.mousePoint, this.parentSurface.seriesViewRect);
const xAxis = this.parentSurface.xAxes.get(0);
const yAxis = this.parentSurface.yAxes.get(0);
const x = point ? xAxis.getCurrentCoordinateCalculator().getDataValue(point.x) : NaN;
const y = point ? yAxis.getCurrentCoordinateCalculator().getDataValue(point.y) : NaN;
const county = point ? this.findCounty(x, y) : undefined;

if (county !== this.hoveredCounty) {
this.hoveredCounty = county;
this.highlight.clear();
if (county) {
const { xValues, yValues } = ringsToLine(county.rings, true);
this.highlight.appendRange(xValues, yValues);
}
}
if (county) {
const format = (value, digits) => value.toLocaleString("en-US", { maximumFractionDigits: digits });
const nearRightEdge = x > xAxis.visibleRange.min + xAxis.visibleRange.diff * 0.6;
this.tooltip.text = [
`${county.name}, ${county.state}`,
`${format(county.density, county.density < 10 ? 1 : 0)} people per sq mile`,
`Population ${format(county.population, 0)} (${format(county.dotCount, 0)} dots)`,
`Land area ${format(county.landArea, 1)} sq miles`
].join("\n");
this.tooltip.horizontalAnchorPoint = nearRightEdge ? EHorizontalAnchorPoint.Right : EHorizontalAnchorPoint.Left;
// Offsets are a fraction of the visible range, so the gap from the cursor looks the same at every zoom level
this.tooltip.x1 = x + xAxis.visibleRange.diff * (nearRightEdge ? -0.012 : 0.012);
this.tooltip.y1 = y + yAxis.visibleRange.diff * 0.03;
}
this.tooltip.isHidden = !county;
}

modifierMouseLeave(args) {
super.modifierMouseLeave(args);
this.tooltip.isHidden = true;
this.hoveredCounty = undefined;
this.highlight.clear();
}
}

// 4. THE CHART
// data: counties grouped by state, with outlines in kilometres (Albers equal-area projection),
// such as getUsCountyData() at the end of this file
async function populationDensityMap(divElementId, data) {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(divElementId, {
theme: new SciChartJsNavyTheme()
});

// A map needs no axis labels, but the hidden axes still set the drawing area, so zoom and pan work as usual.
// The extra space leaves room for the buttons (top), the legend (right) and the SciChart logo (bottom).
const xAxis = new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.02, 0.22) });
const yAxis = new NumericAxis(wasmContext, { isVisible: false, growBy: new NumberRange(0.1, 0.12) });
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);

// Unpack the counties: outlines, triangles (for the fill and the dots), bounds and figures
const counties = [];
data.counties.forEach(([state, names, populations, landAreas, outlines]) => {
const nameList = names.split("|");
outlines.split(",").forEach((encodedRings, i) => {
const rings = encodedRings.split(" ").map(decodeOutline);
const triangles = rings.flatMap((ring) => triangulateRing(ring));
const cumulativeAreas = [];
let area = 0;
for (let t = 0; t < triangles.length; t += 3) {
const [a, b, c] = [triangles[t], triangles[t + 1], triangles[t + 2]];
area += Math.abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2;
cumulativeAreas.push(area);
}
const xs = rings.flat().map((p) => p[0]);
const ys = rings.flat().map((p) => p[1]);
counties.push({
name: nameList[i],
state,
population: populations[i],
landArea: landAreas[i],
density: populations[i] / landAreas[i],
dotCount: 0, // set by setDotValue()
rings,
triangles,
cumulativeAreas,
bounds: { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) }
});
});
});

// Choropleth: one triangle series per class, holding the triangles of every county in that class.
// Denser classes are drawn last, so a city drawn over the county around it stays visible.
const choroplethSeries = DENSITY_CLASSES.map((densityClass, classIndex) => {
const triangles = counties
.filter((county) => getClassIndex(county.density) === classIndex)
.flatMap((county) => county.triangles);
return new FastTriangleRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, {
xValues: triangles.map((p) => p[0]),
yValues: triangles.map((p) => p[1])
}),
drawMode: ETriangleSeriesDrawMode.List, // every three points are one triangle
fill: densityClass.color
});
});
const countyBorders = new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, {
...ringsToLine(
counties.flatMap((county) => county.rings),
true
),
isSorted: false,
containsNaN: true
}),
stroke: "#0B142480",
strokeThickness: 1
});

// Dot density: up to 1.6 million dots in one scatter series, refilled when the dot value changes
const dotData = new XyDataSeries(wasmContext, { isSorted: false, containsNaN: false });
const dotMarker = new SquarePointMarker(wasmContext, { width: 1, height: 1, strokeThickness: 0 });
const dotSeries = new XyScatterRenderableSeries(wasmContext, { dataSeries: dotData, pointMarker: dotMarker });

// State borders and the coast, and the hovered county's outline (filled in by the tooltip modifier)
const stateBorders = new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, {
...ringsToLine(data.stateBorders.split(" ").map(decodeOutline), false),
isSorted: false,
containsNaN: true
}),
strokeThickness: 1.5
});
const highlight = new XyDataSeries(wasmContext, { isSorted: false, containsNaN: true });
sciChartSurface.renderableSeries.add(
...choroplethSeries,
countyBorders,
dotSeries,
stateBorders,
new FastLineRenderableSeries(wasmContext, { dataSeries: highlight, stroke: "#FFFFFF", strokeThickness: 2.5 })
);

// Legends: annotations in relative coordinates (0 to 1 across the chart), so they stay put when you zoom
const relative = { xCoordinateMode: ECoordinateMode.Relative, yCoordinateMode: ECoordinateMode.Relative };
const text = (x1, y1, value, fontSize) =>
new NativeTextAnnotation({
...relative,
x1,
y1,
text: value,
textColor: "#FFFFFF",
fontSize,
multiLineAlignment: EMultiLineAlignment.Left,
lineSpacing: 3,
verticalAnchorPoint: EVerticalAnchorPoint.Center
});
const choroplethLegend = [
new BoxAnnotation({ ...relative, x1: 0.81, x2: 0.995, y1: 0.5, y2: 0.97, fill: "#0F1A2BDD", strokeThickness: 0 }),
text(0.825, 0.565, "People per sq mile\n(2020 Census)", 16)
];
DENSITY_CLASSES.forEach((densityClass, i) => {
const y = 0.65 + i * 0.062;
choroplethLegend.push(
new BoxAnnotation({ ...relative, x1: 0.825, x2: 0.85, y1: y, y2: y + 0.045, fill: densityClass.color, strokeThickness: 0 }),
text(0.86, y + 0.0225, densityClass.label, 15)
);
});
const dotKey = new BoxAnnotation({ ...relative, x1: 0.825, x2: 0.833, y1: 0.8, y2: 0.814, fill: "#FFD166", strokeThickness: 0 });
const dotValueText = text(0.845, 0.807, "", 15);
const dotCountText = text(0.825, 0.895, "", 15);
const dotLegend = [
new BoxAnnotation({ ...relative, x1: 0.81, x2: 0.995, y1: 0.74, y2: 0.97, fill: "#0F1A2BDD", strokeThickness: 0 }),
dotKey,
dotValueText,
dotCountText
];
sciChartSurface.annotations.add(...choroplethLegend, ...dotLegend);

// Change the dot value: recount the dots per county (rounded, so a county of under half a dot gets none),
// place them again with the same seed, and restyle the dots
const setDotValue = (peoplePerDot) => {
const style = DOT_STYLES.find((s) => s.peoplePerDot === peoplePerDot);
counties.forEach((county) => (county.dotCount = Math.round(county.population / peoplePerDot)));
const dots = placeDots(counties, createRandom(2020));
dotData.clear();
dotData.appendRange(dots.xValues, dots.yValues);
dotMarker.fill = style.fill;
dotMarker.width = style.size;
dotMarker.height = style.size;
dotValueText.text = `1 dot = ${peoplePerDot.toLocaleString("en-US")} people`;
dotCountText.text = `${dots.total.toLocaleString("en-US")} dots\n(2020 Census)`;
};
setDotValue(DOT_STYLES[0].peoplePerDot);

// Switch between the two views by showing and hiding series and legends
const showView = (view) => {
const isDots = view === "dots";
choroplethSeries.forEach((series) => (series.isVisible = !isDots));
countyBorders.isVisible = !isDots;
dotSeries.isVisible = isDots;
stateBorders.stroke = isDots ? "#8A9AB5" : "#0B1424";
choroplethLegend.forEach((annotation) => (annotation.isHidden = isDots));
dotLegend.forEach((annotation) => (annotation.isHidden = !isDots));
};
showView("choropleth");

// Keep the map's shape: one kilometre on the x axis must take the same space as one on the y axis
sciChartSurface.preRender.subscribe(() => {
const rect = sciChartSurface.seriesViewRect;
if (!rect || !rect.width || !rect.height) return; // not laid out yet
const { width, height } = rect;
const xRange = xAxis.visibleRange;
const yRange = yAxis.visibleRange;
const kmPerPixel = Math.max(xRange.diff / width, yRange.diff / height);
const xCentre = (xRange.min + xRange.max) / 2;
const yCentre = (yRange.min + yRange.max) / 2;
const newX = new NumberRange(xCentre - (kmPerPixel * width) / 2, xCentre + (kmPerPixel * width) / 2);
const newY = new NumberRange(yCentre - (kmPerPixel * height) / 2, yCentre + (kmPerPixel * height) / 2);
if (Math.abs(newX.diff - xRange.diff) > 1e-6) xAxis.visibleRange = newX;
if (Math.abs(newY.diff - yRange.diff) > 1e-6) yAxis.visibleRange = newY;
});

sciChartSurface.chartModifiers.add(
new CountyTooltipModifier(counties, highlight),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface, showView, setDotValue };
}

Key points:

  • The choropleth is five FastTriangleRenderableSeries, one per density class. triangulateRing cuts each county outline into triangles by ear clipping, and ETriangleSeriesDrawMode.List draws every three points as one triangle.
  • The dots are one XyScatterRenderableSeries with a one-pixel SquarePointMarker and a see-through fill, so overlapping dots add up to brighter areas. placeDots picks a triangle in proportion to its area, then a random point inside it, with a seeded random generator so the map is the same every time. Changing the dot value refills the same data series.
  • Hover is a custom modifier (CountyTooltipModifier, based on CustomChartModifier2D) that converts the mouse position to map coordinates and runs a point-in-polygon test. A preRender handler keeps one kilometre the same size on both axes, so the map isn't stretched.
  • The 3D map above uses a ColumnRenderableSeries3D with a colour per column (useMetadataColors), and a PointLineRenderableSeries3D with isLineStrip: false for the state borders on the floor. Open its code with the CodePen link under the 3D demo.

See it in the demo app: JavaScript choropleth map · React choropleth map · Angular choropleth map. Related demos: a heatmap over a map and a 3D column chart.

Go deeper: SciChart.js choropleth map documentation and SciChart.js 3D column chart documentation.

Frequently asked questions​

What does a population density map show?​

A population density map shows where people live closely packed and where they are spread thinly. Each area, square or dot stands for people per unit of land, such as people per square mile, so you can see cities, corridors along coasts and rivers, and empty regions. It does not show how many people live in an area in total: a big, sparse county can hold more people than a small, dense one.

What type of map shows population density?​

Population density is most often shown on a choropleth map, which shades each area, such as a county or country, by its people per square mile or square kilometre. A dot density map shows it with one dot for a fixed number of people, so dots crowd together where density is high. Grid maps use equal squares or hexagons instead of areas, and 3D maps raise each area or square to a height set by its density. All of them are thematic maps.

How is population density calculated?​

Population density is the number of people divided by the land area they live on. Kershaw County, South Carolina, had 65,403 people on 726.6 square miles of land in 2020, so its density was 90 people per square mile. Official figures usually use land area only, leaving out lakes and the sea. To convert people per square mile to people per square kilometre, divide by 2.59.

What is the difference between a dot density map and a choropleth map?​

A choropleth map shades each whole area by one value, such as its population density, so you read the colour against a legend. A dot density map draws one dot for a fixed number of people, such as 1 dot = 1,000 people, inside each area, so you see density from how closely the dots are packed. The choropleth gives each area's exact class; the dot density map shows the total number of people too, but where each dot falls within its area is chosen at random.

Are 3D population density maps a good idea?​

3D population density maps are good at showing where people are concentrated: a few tall columns over the big cities stand out at once. They are poor at exact comparison, because tall columns hide the ones behind them, perspective makes far columns look shorter, and people judge heights less accurately than positions on a flat scale. Use them with tooltips, a top-down view or a 2D map beside them.

How do I make a population density map in JavaScript?​

Load the area outlines as GeoJSON or another polygon format, join each area's population and land area to it, and divide one by the other for the density. With SciChart.js, cut the outlines into triangles and draw them with a FastTriangleRenderableSeries, one series per colour class, for a choropleth. For a dot density map, put random points inside each area and draw them all in one XyScatterRenderableSeries, which stays smooth with over a million dots. For 3D, use a ColumnRenderableSeries3D. The same code runs in React or Angular through scichart-react or scichart-angular.

Sources​