{"spec_id":"scatter-hr-diagram","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-hr-diagram: Hertzsprung-Russell Diagram\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsAxis } from \"@mui/x-charts/ChartsAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SPECTRAL_SEQUENCE = [\"O\", \"B\", \"A\", \"F\", \"G\", \"K\", \"M\"]; // hottest to coolest\n// Conventional star colours (blue O/B, white A, yellow F/G, orange K, red M) mapped to the\n// nearest Imprint palette members: the palette has no white, so lavender, its palest hue, stands\n// in for A, and lime, its yellowest hue next to the ochre of G, stands in for yellow-white F\nconst SPECTRAL_COLORS = {\n  O: t.palette[2],\n  B: t.palette[5],\n  A: t.palette[1],\n  F: t.palette[7],\n  G: t.palette[3],\n  K: t.palette[6],\n  M: t.palette[4],\n};\nconst REFERENCE_LUMINOSITY = 1; // luminosity is in solar units, so the reference star sits at exactly 1\nconst TEMPERATURE_PAD_SHARE = 0.03; // room beyond the hottest and coolest star, as a share of the span\nconst LOG_PAD_SHARE = 0.04; // room above and below the extreme luminosities, as a share of the decades spanned\nconst SUPERSCRIPT_DIGITS = \"⁰¹²³⁴⁵⁶⁷⁸⁹\";\nconst TEMPERATURE_TICK_COUNT = 16; // about this many temperature ticks, one even step across the axis\nconst STAR_OPACITY = 0.8;\nconst STAR_RADIUS = 6; // px\nconst RING_RADIUS = 11; // px around a named star\nconst REFERENCE_RING_RADIUS = 14; // px around the reference star\nconst LABEL_CHAR_WIDTH = 0.6; // average glyph width of the annotation labels, as a share of the font size\nconst LABEL_PAD = 4; // px of clear space kept around each label\nconst LABEL_DIRECTIONS = 8; // candidate label positions around each anchor, starting straight above\nconst LABEL_STEP = 12; // px between successive rings of candidate positions\nconst LABEL_STEPS = 16; // rings tried before a label falls back to its first position\n\n// Columns: set these to your data's column names\nconst TEMPERATURE = \"Surface temperature (K)\"; // role: temperature\nconst LUMINOSITY = \"Luminosity (L/L☉)\"; // role: luminosity\nconst SPECTRAL_TYPE = \"Spectral type\"; // role: spectral_type\nconst STAR_NAME = \"Star\"; // role: star_name\nconst REGION = \"Region\"; // role: region\n\n// Data: replace this block with your own records, one object per row\n// Synthetic stellar populations (main sequence with L ~ T^6, close to the observed\n// slope from M dwarfs to O stars, red giants, supergiants, white dwarfs) plus the\n// Sun and three named stars with approximate literature values. Spectral types\n// follow the Harvard temperature bounds.\nconst data = (() => {\n  let seed = 42;\n  const uniform = (min, max) => {\n    seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n    return min + (seed / 4294967295) * (max - min);\n  };\n  const lowerBounds = [[\"O\", 30000], [\"B\", 10000], [\"A\", 7500], [\"F\", 6000], [\"G\", 5200], [\"K\", 3700], [\"M\", 0]];\n  const star = (temperature, luminosity, region, name = null) => ({\n    [TEMPERATURE]: Math.round(temperature),\n    [LUMINOSITY]: Number(luminosity.toPrecision(4)),\n    [SPECTRAL_TYPE]: lowerBounds.find(([, lower]) => temperature >= lower)[0],\n    [STAR_NAME]: name,\n    [REGION]: region,\n  });\n  const rows = [];\n  for (let k = 0; k < 180; k += 1) {\n    const temperature = uniform(2600, 38000);\n    rows.push(star(temperature, (temperature / 5778) ** 6 * uniform(0.55, 1.8), \"Main sequence\"));\n  }\n  for (let k = 0; k < 40; k += 1) rows.push(star(uniform(3400, 5200), uniform(15, 900), \"Red giants\"));\n  for (let k = 0; k < 25; k += 1) rows.push(star(uniform(3000, 30000), uniform(8000, 800000), \"Supergiants\"));\n  for (let k = 0; k < 35; k += 1) rows.push(star(uniform(8000, 40000), uniform(0.0001, 0.02), \"White dwarfs\"));\n  rows.push(star(5778, 1, \"Main sequence\", \"Sun\"));\n  rows.push(star(9940, 25.4, \"Main sequence\", \"Sirius A\"));\n  rows.push(star(12100, 120000, \"Supergiants\", \"Rigel\"));\n  rows.push(star(3500, 126000, \"Supergiants\", \"Betelgeuse\"));\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst referenceRow = data.find((d) => d[STAR_NAME] && d[LUMINOSITY] === REFERENCE_LUMINOSITY);\nconst stars = data.filter((d) => d !== referenceRow);\n\n// Spectral types in the conventional hot-to-cool order; a type outside it follows in order of appearance\nconst presentTypes = [...new Set(stars.map((d) => d[SPECTRAL_TYPE]))];\nconst types = [\n  ...SPECTRAL_SEQUENCE.filter((s) => presentTypes.includes(s)),\n  ...presentTypes.filter((s) => !SPECTRAL_SEQUENCE.includes(s)),\n];\nconst spareColors = t.palette.filter((c) => !Object.values(SPECTRAL_COLORS).includes(c));\nconst unmappedTypes = types.filter((s) => !(s in SPECTRAL_COLORS));\nconst typeColor = Object.fromEntries(\n  types.map((s) => [s, SPECTRAL_COLORS[s] ?? spareColors[unmappedTypes.indexOf(s)]]),\n);\n\n// Secondary axis: each spectral letter at the middle of its temperature range\nconst classTicks = types.map((s) => {\n  const temps = data.filter((d) => d[SPECTRAL_TYPE] === s).map((d) => d[TEMPERATURE]);\n  return { type: s, at: (Math.min(...temps) + Math.max(...temps)) / 2 };\n});\nconst classByTick = new Map(classTicks.map((c) => [c.at, c.type]));\n\n// Each region label is anchored at the centroid of its own population, in the axes' own spaces;\n// the layer below moves it to the nearest spot beside that population that covers no star\nconst regionLabels = [...new Set(data.map((d) => d[REGION]))].map((region) => {\n  const rows = data.filter((d) => d[REGION] === region);\n  return {\n    text: region,\n    x: rows.reduce((s, d) => s + d[TEMPERATURE], 0) / rows.length,\n    y: 10 ** (rows.reduce((s, d) => s + Math.log10(d[LUMINOSITY]), 0) / rows.length),\n  };\n});\nconst namedStars = data.filter((d) => d[STAR_NAME]);\nconst ringOf = new Map(namedStars.map((d) => [d, d === referenceRow ? REFERENCE_RING_RADIUS : RING_RADIUS]));\n\nconst temps = data.map((d) => d[TEMPERATURE]);\nconst tPad = (Math.max(...temps) - Math.min(...temps)) * TEMPERATURE_PAD_SHARE;\nconst tMin = Math.min(...temps) - tPad;\nconst tMax = Math.max(...temps) + tPad;\nconst logLums = data.map((d) => Math.log10(d[LUMINOSITY]));\nconst logPad = (Math.max(...logLums) - Math.min(...logLums)) * LOG_PAD_SHARE;\nconst logMin = Math.min(...logLums) - logPad;\nconst logMax = Math.max(...logLums) + logPad;\nconst lumTicks = Array.from(\n  { length: Math.floor(logMax) - Math.ceil(logMin) + 1 },\n  (_, k) => 10 ** (Math.ceil(logMin) + k),\n);\n\nconst TITLE = \"scatter-hr-diagram · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length} stars across ${regionLabels.length} regions · colour: ${SPECTRAL_TYPE.toLowerCase()} · ringed: named stars`;\nconst HEADER_HEIGHT = 76;\nconst LEGEND_HEIGHT = 40;\n\nfunction Annotations() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const { left, top, width, height } = useDrawingArea();\n  const obstacles = data.map((d) => ({\n    x: xScale(d[TEMPERATURE]),\n    y: yScale(d[LUMINOSITY]),\n    r: ringOf.get(d) ?? STAR_RADIUS,\n  }));\n  // Named stars first, then the regions; each label takes the first candidate, nearest first,\n  // whose box stays inside the plot and clear of every star, ring and label placed before it\n  const requests = [\n    ...namedStars.map((d) => ({\n      text: d[STAR_NAME],\n      fontSize: d === referenceRow ? 16 : 14,\n      fill: t.ink,\n      ax: xScale(d[TEMPERATURE]),\n      ay: yScale(d[LUMINOSITY]),\n      gap: ringOf.get(d) + LABEL_PAD,\n    })),\n    ...regionLabels.map((r) => ({ text: r.text, fontSize: 17, fill: t.inkSoft, ax: xScale(r.x), ay: yScale(r.y), gap: 0 })),\n  ];\n  const placed: { x: number; y: number; w: number; h: number; text: string; fontSize: number; fill: string }[] = [];\n  requests.forEach((q) => {\n    const w = q.text.length * q.fontSize * LABEL_CHAR_WIDTH + 2 * LABEL_PAD;\n    const h = q.fontSize + 2 * LABEL_PAD;\n    const candidates = Array.from({ length: LABEL_STEPS }, (_, s) => q.gap + s * LABEL_STEP).flatMap((gap) =>\n      Array.from({ length: LABEL_DIRECTIONS }, (_, k) => Math.PI / 2 + (2 * Math.PI * k) / LABEL_DIRECTIONS).map((a) => {\n        const cos = Math.round(Math.cos(a) * 1e6) / 1e6;\n        const sin = Math.round(Math.sin(a) * 1e6) / 1e6;\n        const x = q.ax + (gap === 0 ? 0 : cos * (gap + w / 2));\n        const y = q.ay - (gap === 0 ? 0 : sin * (gap + h / 2));\n        return { x, y };\n      }),\n    );\n    const free = candidates.find(({ x, y }) => {\n      const x0 = x - w / 2;\n      const x1 = x + w / 2;\n      const y0 = y - h / 2;\n      const y1 = y + h / 2;\n      if (x0 < left || x1 > left + width || y0 < top || y1 > top + height) return false;\n      if (obstacles.some((o) => o.x > x0 - o.r && o.x < x1 + o.r && o.y > y0 - o.r && o.y < y1 + o.r)) return false;\n      return !placed.some((p) => x0 < p.x + p.w / 2 && p.x - p.w / 2 < x1 && y0 < p.y + p.h / 2 && p.y - p.h / 2 < y1);\n    });\n    placed.push({ ...(free ?? candidates[0]), w, h, text: q.text, fontSize: q.fontSize, fill: q.fill });\n  });\n  return (\n    <g>\n      {namedStars.map((d) => (\n        <circle\n          key={`ring-${d[STAR_NAME]}`}\n          cx={xScale(d[TEMPERATURE])}\n          cy={yScale(d[LUMINOSITY])}\n          r={ringOf.get(d)}\n          fill=\"none\"\n          stroke={t.ink}\n          strokeWidth={d === referenceRow ? 2.5 : 1.5}\n        />\n      ))}\n      {placed.map((p) => (\n        <text\n          key={`label-${p.text}`}\n          x={p.x}\n          y={p.y}\n          textAnchor=\"middle\"\n          dominantBaseline=\"central\"\n          fontSize={p.fontSize}\n          fontWeight={600}\n          fill={p.fill}\n          stroke={t.pageBg}\n          strokeWidth={4}\n          strokeLinejoin=\"round\"\n          paintOrder=\"stroke\"\n        >\n          {p.text}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_HEIGHT - LEGEND_HEIGHT}\n        margin={{ top: 4, right: 48, bottom: 8, left: 24 }}\n        skipAnimation\n        series={[\n          ...types.map((s) => ({\n            type: \"scatter\" as const,\n            id: `type-${s}`,\n            label: s,\n            color: typeColor[s],\n            markerSize: STAR_RADIUS,\n            data: stars\n              .filter((d) => d[SPECTRAL_TYPE] === s)\n              .map((d, k) => ({ id: `${s}-${k}`, x: d[TEMPERATURE], y: d[LUMINOSITY] })),\n          })),\n          ...(referenceRow\n            ? [\n                {\n                  type: \"scatter\" as const,\n                  id: \"reference\",\n                  label: referenceRow[STAR_NAME],\n                  color: t.ink,\n                  markerSize: 7,\n                  data: [{ id: \"reference\", x: referenceRow[TEMPERATURE], y: referenceRow[LUMINOSITY] }],\n                },\n              ]\n            : []),\n        ]}\n        xAxis={[\n          {\n            id: \"temperature\",\n            scaleType: \"linear\",\n            reverse: true,\n            min: tMin,\n            max: tMax,\n            label: TEMPERATURE,\n            tickNumber: TEMPERATURE_TICK_COUNT,\n            height: 64,\n            valueFormatter: (v: number) => v.toLocaleString(\"en-US\"),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n          {\n            id: \"spectral\",\n            scaleType: \"linear\",\n            reverse: true,\n            position: \"top\",\n            min: tMin,\n            max: tMax,\n            label: SPECTRAL_TYPE,\n            height: 60,\n            tickInterval: classTicks.map((c) => c.at),\n            tickLabelInterval: () => true,\n            valueFormatter: (v: number) => classByTick.get(v) ?? \"\",\n            tickLabelStyle: { fontSize: 16, fontWeight: 600, fill: t.ink },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"luminosity\",\n            scaleType: \"log\",\n            min: 10 ** logMin,\n            max: 10 ** logMax,\n            label: LUMINOSITY,\n            width: 84,\n            tickInterval: lumTicks,\n            valueFormatter: (v: number, ctx) => {\n              if (ctx.location !== \"tick\") return v.toPrecision(3);\n              const exponent = Math.round(Math.log10(v));\n              const digits = [...String(Math.abs(exponent))].map((c) => SUPERSCRIPT_DIGITS[Number(c)]).join(\"\");\n              return exponent === 0 ? \"1\" : `10${exponent < 0 ? \"⁻\" : \"\"}${digits}`;\n            },\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"center\" }} legendDirection=\"horizontal\">\n          <ChartsLegend sx={{ fontSize: 16, color: t.ink, height: LEGEND_HEIGHT, alignItems: \"center\" }} />\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiScatterChart-marker\": { fillOpacity: STAR_OPACITY, stroke: t.pageBg, strokeWidth: 1 },\n              '& [data-series=\"reference\"] .MuiScatterChart-marker': { fillOpacity: 1 },\n            }}\n          >\n            <ChartsGrid horizontal vertical />\n            <ChartsAxis />\n            <ScatterPlot />\n            <Annotations />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}