{"spec_id":"cartogram-area-distortion","library":"d3","language":"javascript","code":"// anyplot.ai\n// cartogram-area-distortion: Cartogram with Area Distortion by Data Value\n// Library: d3 7.9.0 | JavaScript 22.23.4\n// Quality: 82/100 | Updated: 2026-11-08\n\nconst t = window.ANYPLOT_TOKENS;\nconst { width, height } = window.ANYPLOT_SIZE;\n\nconst margin = { top: 130, right: 250, bottom: 50, left: 30 };\nconst iw = width - margin.left - margin.right;\nconst ih = height - margin.top - margin.bottom;\n\n// Columns: set these to your data's column names\nconst REGION = \"State\";  // role: region\nconst LABEL = \"Abbreviation\";  // role: label\nconst LON = \"Longitude\";  // role: x (centroid)\nconst LAT = \"Latitude\";  // role: y (centroid)\nconst VALUE = \"Population (millions)\";  // role: value (area)\nconst SECONDARY = \"GDP per capita (USD)\";  // role: color\n\n// Data: replace this block with your own records, one object per row\n// US states + D.C.: centroid, population 2023, GDP per capita 2022\nconst data = [\n  { [REGION]: \"Alabama\",        [LABEL]: \"AL\", [LON]: -86.7,  [LAT]: 32.8, [VALUE]: 5.1,  [SECONDARY]: 53100  },\n  { [REGION]: \"Alaska\",         [LABEL]: \"AK\", [LON]: -153.0, [LAT]: 64.2, [VALUE]: 0.74, [SECONDARY]: 82400  },\n  { [REGION]: \"Arizona\",        [LABEL]: \"AZ\", [LON]: -111.7, [LAT]: 34.3, [VALUE]: 7.4,  [SECONDARY]: 65900  },\n  { [REGION]: \"Arkansas\",       [LABEL]: \"AR\", [LON]: -92.4,  [LAT]: 34.9, [VALUE]: 3.1,  [SECONDARY]: 50000  },\n  { [REGION]: \"California\",     [LABEL]: \"CA\", [LON]: -119.7, [LAT]: 37.2, [VALUE]: 39.0, [SECONDARY]: 99700  },\n  { [REGION]: \"Colorado\",       [LABEL]: \"CO\", [LON]: -105.5, [LAT]: 39.0, [VALUE]: 5.9,  [SECONDARY]: 84400  },\n  { [REGION]: \"Connecticut\",    [LABEL]: \"CT\", [LON]: -72.7,  [LAT]: 41.6, [VALUE]: 3.6,  [SECONDARY]: 91900  },\n  { [REGION]: \"Delaware\",       [LABEL]: \"DE\", [LON]: -75.5,  [LAT]: 39.0, [VALUE]: 1.0,  [SECONDARY]: 91000  },\n  { [REGION]: \"Florida\",        [LABEL]: \"FL\", [LON]: -81.5,  [LAT]: 27.8, [VALUE]: 22.6, [SECONDARY]: 64600  },\n  { [REGION]: \"Georgia\",        [LABEL]: \"GA\", [LON]: -83.4,  [LAT]: 32.7, [VALUE]: 11.0, [SECONDARY]: 67500  },\n  { [REGION]: \"Hawaii\",         [LABEL]: \"HI\", [LON]: -157.5, [LAT]: 20.3, [VALUE]: 1.44, [SECONDARY]: 66700  },\n  { [REGION]: \"Idaho\",          [LABEL]: \"ID\", [LON]: -114.5, [LAT]: 44.4, [VALUE]: 2.0,  [SECONDARY]: 55000  },\n  { [REGION]: \"Illinois\",       [LABEL]: \"IL\", [LON]: -89.2,  [LAT]: 40.1, [VALUE]: 12.6, [SECONDARY]: 81200  },\n  { [REGION]: \"Indiana\",        [LABEL]: \"IN\", [LON]: -86.3,  [LAT]: 40.0, [VALUE]: 6.9,  [SECONDARY]: 62600  },\n  { [REGION]: \"Iowa\",           [LABEL]: \"IA\", [LON]: -93.5,  [LAT]: 42.1, [VALUE]: 3.2,  [SECONDARY]: 71600  },\n  { [REGION]: \"Kansas\",         [LABEL]: \"KS\", [LON]: -98.4,  [LAT]: 38.5, [VALUE]: 2.9,  [SECONDARY]: 71400  },\n  { [REGION]: \"Kentucky\",       [LABEL]: \"KY\", [LON]: -84.3,  [LAT]: 37.5, [VALUE]: 4.5,  [SECONDARY]: 58400  },\n  { [REGION]: \"Louisiana\",      [LABEL]: \"LA\", [LON]: -91.8,  [LAT]: 31.2, [VALUE]: 4.6,  [SECONDARY]: 60700  },\n  { [REGION]: \"Maine\",          [LABEL]: \"ME\", [LON]: -69.2,  [LAT]: 45.4, [VALUE]: 1.4,  [SECONDARY]: 56400  },\n  { [REGION]: \"Maryland\",       [LABEL]: \"MD\", [LON]: -76.8,  [LAT]: 39.1, [VALUE]: 6.2,  [SECONDARY]: 82400  },\n  { [REGION]: \"Massachusetts\",  [LABEL]: \"MA\", [LON]: -71.8,  [LAT]: 42.3, [VALUE]: 7.1,  [SECONDARY]: 99900  },\n  { [REGION]: \"Michigan\",       [LABEL]: \"MI\", [LON]: -84.5,  [LAT]: 44.3, [VALUE]: 10.0, [SECONDARY]: 63400  },\n  { [REGION]: \"Minnesota\",      [LABEL]: \"MN\", [LON]: -94.3,  [LAT]: 46.4, [VALUE]: 5.7,  [SECONDARY]: 87900  },\n  { [REGION]: \"Mississippi\",    [LABEL]: \"MS\", [LON]: -89.7,  [LAT]: 32.7, [VALUE]: 3.0,  [SECONDARY]: 46300  },\n  { [REGION]: \"Missouri\",       [LABEL]: \"MO\", [LON]: -92.6,  [LAT]: 38.4, [VALUE]: 6.2,  [SECONDARY]: 63700  },\n  { [REGION]: \"Montana\",        [LABEL]: \"MT\", [LON]: -109.6, [LAT]: 47.0, [VALUE]: 1.1,  [SECONDARY]: 61800  },\n  { [REGION]: \"Nebraska\",       [LABEL]: \"NE\", [LON]: -99.9,  [LAT]: 41.5, [VALUE]: 2.0,  [SECONDARY]: 81500  },\n  { [REGION]: \"Nevada\",         [LABEL]: \"NV\", [LON]: -116.7, [LAT]: 39.5, [VALUE]: 3.2,  [SECONDARY]: 76300  },\n  { [REGION]: \"New Hampshire\",  [LABEL]: \"NH\", [LON]: -71.6,  [LAT]: 43.7, [VALUE]: 1.4,  [SECONDARY]: 77900  },\n  { [REGION]: \"New Jersey\",     [LABEL]: \"NJ\", [LON]: -74.5,  [LAT]: 40.1, [VALUE]: 9.3,  [SECONDARY]: 80400  },\n  { [REGION]: \"New Mexico\",     [LABEL]: \"NM\", [LON]: -106.1, [LAT]: 34.5, [VALUE]: 2.1,  [SECONDARY]: 62400  },\n  { [REGION]: \"New York\",       [LABEL]: \"NY\", [LON]: -75.5,  [LAT]: 42.9, [VALUE]: 19.8, [SECONDARY]: 103700 },\n  { [REGION]: \"North Carolina\", [LABEL]: \"NC\", [LON]: -79.4,  [LAT]: 35.6, [VALUE]: 10.7, [SECONDARY]: 66700  },\n  { [REGION]: \"North Dakota\",   [LABEL]: \"ND\", [LON]: -100.5, [LAT]: 47.5, [VALUE]: 0.78, [SECONDARY]: 91000  },\n  { [REGION]: \"Ohio\",           [LABEL]: \"OH\", [LON]: -82.8,  [LAT]: 40.4, [VALUE]: 11.8, [SECONDARY]: 71000  },\n  { [REGION]: \"Oklahoma\",       [LABEL]: \"OK\", [LON]: -97.5,  [LAT]: 35.5, [VALUE]: 4.0,  [SECONDARY]: 59800  },\n  { [REGION]: \"Oregon\",         [LABEL]: \"OR\", [LON]: -120.5, [LAT]: 43.9, [VALUE]: 4.3,  [SECONDARY]: 80700  },\n  { [REGION]: \"Pennsylvania\",   [LABEL]: \"PA\", [LON]: -77.2,  [LAT]: 40.6, [VALUE]: 13.1, [SECONDARY]: 69700  },\n  { [REGION]: \"Rhode Island\",   [LABEL]: \"RI\", [LON]: -71.5,  [LAT]: 41.7, [VALUE]: 1.1,  [SECONDARY]: 71800  },\n  { [REGION]: \"South Carolina\", [LABEL]: \"SC\", [LON]: -80.9,  [LAT]: 33.8, [VALUE]: 5.3,  [SECONDARY]: 53000  },\n  { [REGION]: \"South Dakota\",   [LABEL]: \"SD\", [LON]: -100.3, [LAT]: 44.4, [VALUE]: 0.91, [SECONDARY]: 78000  },\n  { [REGION]: \"Tennessee\",      [LABEL]: \"TN\", [LON]: -86.3,  [LAT]: 35.9, [VALUE]: 7.1,  [SECONDARY]: 67700  },\n  { [REGION]: \"Texas\",          [LABEL]: \"TX\", [LON]: -99.3,  [LAT]: 31.5, [VALUE]: 30.1, [SECONDARY]: 78200  },\n  { [REGION]: \"Utah\",           [LABEL]: \"UT\", [LON]: -111.1, [LAT]: 39.3, [VALUE]: 3.4,  [SECONDARY]: 79400  },\n  { [REGION]: \"Vermont\",        [LABEL]: \"VT\", [LON]: -72.7,  [LAT]: 44.0, [VALUE]: 0.65, [SECONDARY]: 61500  },\n  { [REGION]: \"Virginia\",       [LABEL]: \"VA\", [LON]: -79.4,  [LAT]: 37.5, [VALUE]: 8.7,  [SECONDARY]: 80900  },\n  { [REGION]: \"Washington\",     [LABEL]: \"WA\", [LON]: -120.5, [LAT]: 47.4, [VALUE]: 7.9,  [SECONDARY]: 99400  },\n  { [REGION]: \"West Virginia\",  [LABEL]: \"WV\", [LON]: -80.6,  [LAT]: 38.6, [VALUE]: 1.8,  [SECONDARY]: 49400  },\n  { [REGION]: \"Wisconsin\",      [LABEL]: \"WI\", [LON]: -90.0,  [LAT]: 44.6, [VALUE]: 5.9,  [SECONDARY]: 73400  },\n  { [REGION]: \"Wyoming\",        [LABEL]: \"WY\", [LON]: -107.6, [LAT]: 43.0, [VALUE]: 0.58, [SECONDARY]: 79300  },\n  { [REGION]: \"D.C.\",           [LABEL]: \"DC\", [LON]: -77.0,  [LAT]: 38.9, [VALUE]: 0.69, [SECONDARY]: 234800 },\n];\n\n// Plot: reads only data and the constants above\nconst regions = data.filter((d) => d[VALUE] != null);\n\n// AlbersUSA composite projection places AK + HI in their conventional insets\nconst geoFeatures = {\n  type: \"FeatureCollection\",\n  features: regions.map((d) => ({\n    type: \"Feature\",\n    geometry: { type: \"Point\", coordinates: [d[LON], d[LAT]] },\n  })),\n};\n\nconst projection = d3.geoAlbersUsa().fitExtent([[0, 12], [iw, ih]], geoFeatures);\n\nconst nodes = regions.map((d) => {\n  const p = projection([d[LON], d[LAT]]) ?? [iw / 2, ih / 2];\n  return { d, x: p[0], y: p[1], x0: p[0], y0: p[1] };\n});\n\n// Area ∝ value: radius on a square-root scale\nconst maxR = 70;\nconst rScale = d3.scaleSqrt().domain([0, d3.max(regions, (d) => d[VALUE])]).range([0, maxR]);\n\n// Dorling layout: pull circles to their centroids, collide to remove overlaps\nconst sim = d3.forceSimulation(nodes)\n  .force(\"attract-x\", d3.forceX((n) => n.x0).strength(0.65))\n  .force(\"attract-y\", d3.forceY((n) => n.y0).strength(0.65))\n  .force(\"collide\", d3.forceCollide((n) => rScale(n.d[VALUE]) + 2).strength(1.0))\n  .stop();\nfor (let i = 0; i < 350; i++) sim.tick();\n\n// Color domain ends at the 95th percentile so a single outlier (D.C.) does not\n// flatten the ramp for every other region; values above it clamp to the top stop\nconst secValues = regions.map((d) => d[SECONDARY]).filter((v) => v != null);\nconst secLo = d3.min(secValues);\nconst secHi = d3.quantile(secValues, 0.95);\nconst colorScale = d3.scaleSequential(d3.interpolateRgbBasis(t.seq))\n  .domain([secLo, secHi])\n  .clamp(true);\nconst fmtK = (v) => `$${Math.round(v / 1000)}k`;\n\nconst svg = d3.select(\"#container\").append(\"svg\").attr(\"width\", width).attr(\"height\", height);\nconst g = svg.append(\"g\").attr(\"transform\", `translate(${margin.left},${margin.top})`);\n\n// Larger circles first so smaller neighbours stay on top\nconst sorted = [...nodes].sort((a, b) => b.d[VALUE] - a.d[VALUE]);\n\ng.selectAll(\"circle.region\")\n  .data(sorted)\n  .join(\"circle\")\n  .attr(\"class\", \"region\")\n  .attr(\"cx\", (n) => n.x)\n  .attr(\"cy\", (n) => n.y)\n  .attr(\"r\", (n) => rScale(n.d[VALUE]))\n  .attr(\"fill\", (n) => (n.d[SECONDARY] == null ? t.grid : colorScale(n.d[SECONDARY])))\n  .attr(\"stroke\", t.pageBg)\n  .attr(\"stroke-width\", 1.5);\n\n// Two letters at 11 px need a radius of about 11 px; smaller circles stay unlabeled\nconst minLabelR = 11;\ng.selectAll(\"text.abbr\")\n  .data(sorted.filter((n) => rScale(n.d[VALUE]) >= minLabelR))\n  .join(\"text\")\n  .attr(\"class\", \"abbr\")\n  .attr(\"x\", (n) => n.x)\n  .attr(\"y\", (n) => n.y)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"dominant-baseline\", \"central\")\n  .attr(\"fill\", t.pageBg)\n  .style(\"font-size\", (n) => `${Math.max(11, Math.min(18, rScale(n.d[VALUE]) * 0.46))}px`)\n  .style(\"font-weight\", \"700\")\n  .style(\"pointer-events\", \"none\")\n  .text((n) => n.d[LABEL]);\n\n// Title\nconst titleStr = \"US Population Cartogram · cartogram-area-distortion · javascript · d3 · anyplot.ai\";\nconst titlePx = Math.round(22 * Math.min(1, 67 / titleStr.length));\nsvg.append(\"text\")\n  .attr(\"x\", width / 2)\n  .attr(\"y\", 52)\n  .attr(\"text-anchor\", \"middle\")\n  .attr(\"fill\", t.ink)\n  .style(\"font-size\", `${titlePx}px`)\n  .style(\"font-weight\", \"600\")\n  .text(titleStr);\n\n// Subtitle sits below the title band so it clears the northernmost circles\nsvg.append(\"text\")\n  .attr(\"x\", margin.left)\n  .attr(\"y\", 96)\n  .attr(\"fill\", t.inkSoft)\n  .style(\"font-size\", \"14px\")\n  .text(`Circle area ∝ ${VALUE.toLowerCase()} · Color = ${SECONDARY}`);\n\n// Legend column to the right of the map, so no legend element covers a circle\nconst legX = margin.left + iw + 28;\nconst colW = width - legX - 16;\nconst legendTitle = (y, text) =>\n  svg.append(\"text\")\n    .attr(\"x\", legX)\n    .attr(\"y\", y)\n    .attr(\"fill\", t.ink)\n    .style(\"font-size\", \"14px\")\n    .style(\"font-weight\", \"600\")\n    .text(text);\n\n// Color legend\nconst legY = margin.top + 10;\nconst legH = 170;\nconst legW = 16;\n\nconst grad = svg.append(\"defs\").append(\"linearGradient\")\n  .attr(\"id\", \"cleg-grad\")\n  .attr(\"x1\", \"0%\").attr(\"y1\", \"100%\")\n  .attr(\"x2\", \"0%\").attr(\"y2\", \"0%\");\nd3.range(0, 1.0001, 0.25).forEach((s) => {\n  grad.append(\"stop\")\n    .attr(\"offset\", `${s * 100}%`)\n    .attr(\"stop-color\", colorScale(secLo + s * (secHi - secLo)));\n});\n\nsvg.append(\"rect\")\n  .attr(\"x\", legX)\n  .attr(\"y\", legY)\n  .attr(\"width\", legW)\n  .attr(\"height\", legH)\n  .attr(\"fill\", \"url(#cleg-grad)\")\n  .attr(\"rx\", 2);\n\nconst cLegScale = d3.scaleLinear().domain([secLo, secHi]).range([legH, 0]);\nconst cAxisG = svg.append(\"g\")\n  .attr(\"transform\", `translate(${legX + legW}, ${legY})`)\n  .call(d3.axisRight(cLegScale).ticks(4).tickFormat(fmtK));\ncAxisG.selectAll(\"text\").attr(\"fill\", t.inkSoft).style(\"font-size\", \"13px\");\ncAxisG.selectAll(\"line\").attr(\"stroke\", t.inkSoft).attr(\"stroke-opacity\", 0.5);\ncAxisG.select(\".domain\").remove();\n\nlegendTitle(legY - 12, \"GDP / capita\");\n\nconst nAbove = secValues.filter((v) => v > secHi).length;\nif (nAbove > 0) {\n  svg.append(\"text\")\n    .attr(\"x\", legX)\n    .attr(\"y\", legY + legH + 22)\n    .attr(\"fill\", t.inkSoft)\n    .style(\"font-size\", \"13px\")\n    .text(`top color = ${fmtK(secHi)} and above`);\n}\n\n// Size legend: nested circles at round values of the data range\nconst szLegY = legY + legH + 72;\nlegendTitle(szLegY - 12, \"Population\");\n\nconst szMax = d3.max(regions, (d) => d[VALUE]);\nconst szVals = [1, 10, 30].filter((v) => v <= szMax);\nconst szR = rScale(d3.max(szVals));\nconst szCx = legX + szR + 2;\nconst szBase = szLegY + 2 * szR;\nszVals.forEach((v) => {\n  const r = rScale(v);\n  const cy = szBase - r;\n  svg.append(\"circle\")\n    .attr(\"cx\", szCx)\n    .attr(\"cy\", cy)\n    .attr(\"r\", r)\n    .attr(\"fill\", \"none\")\n    .attr(\"stroke\", t.inkSoft)\n    .attr(\"stroke-width\", 1)\n    .attr(\"stroke-dasharray\", \"3,2\");\n  svg.append(\"line\")\n    .attr(\"x1\", szCx)\n    .attr(\"y1\", cy - r)\n    .attr(\"x2\", szCx + szR + 8)\n    .attr(\"y2\", cy - r)\n    .attr(\"stroke\", t.inkSoft)\n    .attr(\"stroke-width\", 1);\n  svg.append(\"text\")\n    .attr(\"x\", szCx + szR + 12)\n    .attr(\"y\", cy - r + 4)\n    .attr(\"fill\", t.inkSoft)\n    .style(\"font-size\", \"13px\")\n    .text(`${v}M`);\n});\n\n// Reference inset: equal-size dots at true positions, for comparison with the cartogram\nconst insetY = szBase + 52;\n// AlbersUSA spans roughly 1.6 : 1, so the box follows that aspect within the free column height\nconst insetH = Math.min(height - margin.bottom - insetY + 20, colW * 0.66);\nlegendTitle(insetY - 12, \"Actual geography\");\n\nconst inset = svg.append(\"g\").attr(\"transform\", `translate(${legX},${insetY})`);\ninset.append(\"rect\")\n  .attr(\"width\", colW)\n  .attr(\"height\", insetH)\n  .attr(\"fill\", t.elevatedBg)\n  .attr(\"stroke\", t.grid)\n  .attr(\"stroke-width\", 1)\n  .attr(\"rx\", 4);\n\nconst insetProj = d3.geoAlbersUsa().fitExtent([[8, 8], [colW - 8, insetH - 8]], geoFeatures);\ninset.selectAll(\"circle\")\n  .data(regions)\n  .join(\"circle\")\n  .attr(\"cx\", (d) => insetProj([d[LON], d[LAT]])?.[0] ?? -99)\n  .attr(\"cy\", (d) => insetProj([d[LON], d[LAT]])?.[1] ?? -99)\n  .attr(\"r\", 4)\n  .attr(\"fill\", (d) => (d[SECONDARY] == null ? t.grid : colorScale(d[SECONDARY])))\n  .attr(\"stroke\", t.pageBg)\n  .attr(\"stroke-width\", 0.6);\n"}