Skip to main content

Hertzsprung–Russell (HR) Diagram

What is an HR diagram?​

A Hertzsprung–Russell diagram (HR diagram, or H-R diagram) is a scatter plot of stars: each star's luminosity, or absolute magnitude, against its surface temperature, colour index or spectral class. Temperature runs backwards, with the hottest stars on the left, and luminosity is on a log scale. Most stars fall on one diagonal band, the main sequence.

An HR diagram of 9,000 simulated stars on a dark navy background, coloured from blue for the hottest to orange-red for the coolest. Surface temperature runs from 40,000 K on the left to 2,500 K on the right, and luminosity from 0.0001 to a million times the Sun's on a log scale. A diagonal main sequence, a giant branch rising to the upper right, a scatter of supergiants along the top and a white dwarf sequence at the lower left are labelled, with the Sun marked and the spectral classes O to M along the top

An HR diagram of 9,000 simulated stars, coloured by temperature, with the main regions and spectral classes labelled. Try the interactive version.

Key takeaways
  • Up means more luminous; left means hotter. Both axes are usually logarithmic.
  • The main sequence is where stars spend most of their lives, fusing hydrogen in their cores. Mass sets a star's place along it.
  • Giants and supergiants sit above it to the right (cool but huge); white dwarfs sit below it to the left (hot but tiny).
  • In a star cluster, the point where the main sequence ends, the turn-off, tells you the cluster's age.
  • A colour-magnitude diagram is the same chart built from measured colour and absolute magnitude instead of temperature and luminosity.

The diagram is named after Ejnar Hertzsprung, who compared the brightness and colour of stars in 1911, and Henry Norris Russell, who plotted their luminosity against spectral class in 1913. Each found, independently, that stars don't scatter at random: a star's temperature and its power output are linked, and the few groups they form are stages of a star's life.

The axes of an HR diagram​

An HR diagram is drawn in two equivalent ways, from theory or from measurements, and the axis labels tell you which one you're looking at.

Theorist's HR diagramObserver's HR diagram (colour-magnitude diagram)
Horizontal axisSurface (effective) temperature in kelvin, log scale, hotter to the leftColour index, such as B-V or Gaia's BP-RP; bluer (hotter) to the left
Vertical axisLuminosity in solar units (L⊙L_\odot), log scaleAbsolute magnitude, such as MVM_V; brighter is up, so the numbers fall upwards
Comes fromModels, or measurements converted to physical unitsTwo brightness measurements and a distance
Used forStellar evolution tracks, comparing with theoryStar clusters, survey data, Gaia and Hipparcos plots

Older diagrams, and many school versions, use spectral class (O, B, A, F, G, K, M) across the bottom instead of temperature. All three run hot to cool from left to right.

Why is temperature backwards on an HR diagram?​

The first diagrams plotted spectral class, written in the order O, B, A, F, G, K, M. That order was later found to run from hottest to coolest, and the axis kept its direction when temperature replaced class. The colour index axis goes the same way naturally: a small or negative B-V means a blue, hot star, and it sits at the left.

Why are the axes logarithmic?​

The brightest stars put out about a million times the Sun's power, and the faintest white dwarfs less than a ten-thousandth of it: more than ten powers of ten. On a linear axis every star except the brightest few would sit squashed against zero. A log scale gives each power of ten the same height, so a white dwarf and a supergiant fit on one chart (see log scale graph). Temperature spans less, about 2,500 K to 50,000 K, but it is logged too, so equal distances mean equal ratios.

Absolute magnitude and colour index​

Absolute magnitude (MM) is how bright a star would look from a standard distance of 10 parsecs (32.6 light years). It is worked out from the apparent magnitude (mm), how bright the star looks from Earth, and its distance dd:

M=m−5log⁡10(d10 pc)M = m - 5\log_{10}\left(\frac{d}{10\ \text{pc}}\right)

ignoring the dimming by interstellar dust. The magnitude scale runs backwards and is logarithmic: 5 magnitudes is a factor of 100 in brightness, and a smaller number is a brighter star. That's why the magnitude axis has its most negative values at the top.

A colour index is the difference between a star's magnitudes through two filters. B-V uses a blue (B) and a visual, yellow-green (V) filter. A hot star is brighter in blue, so its B-V is small or negative; a cool red star has a B-V of 1.5 or more. It stands in for temperature, and a telescope can measure it directly.

Regions of the HR diagram​

Stars on the HR diagram fall into five main regions, the main sequence, subgiants, red giants, supergiants and white dwarfs, and each marks a different stage of a star's life.

A labelled HR diagram: surface temperature from 40,000 K on the left to 2,500 K on the right, luminosity from 0.0001 to a million Suns on a log scale. Coloured bands at the top mark spectral classes O, B, A, F, G, K and M. A blue diagonal band is the main sequence, labelled hydrogen burning in the core, with the Sun on it at 5,772 K and luminosity 1. An orange area above it on the right is the giants, with subgiants between them, a purple band across the top is the supergiants, and a grey area at the lower left is the white dwarfs. Dashed lines mark stars of 0.01, 1 and 100 times the Sun's radius

RegionWhere on the diagramTypical temperatureTypical luminosity (Sun = 1)What the stars are doing
Main sequenceDiagonal band, top left to bottom rightAbout 2,500 K to over 40,000 KAbout 0.001 to 1,000,000Fusing hydrogen into helium in the core
SubgiantsJust above the main sequence, between it and the giantsAbout 5,000 K to 6,500 KAbout 2 to 10Core hydrogen used up; the star starts to swell
Red giantsUpper rightAbout 3,500 K to 5,200 KAbout 10 to 3,000Hydrogen burning in a shell round a helium core, or helium burning in the core (the red clump)
SupergiantsAcross the topAny, from red (3,500 K) to blue (30,000 K)About 10,000 to 1,000,000Massive stars in their late stages
White dwarfsLower leftAbout 5,000 K to over 30,000 KAbout 0.0001 to 0.1Burnt-out cores, about the size of the Earth, cooling

Because a star's power depends on both its temperature and its size, every point also gives a radius. The Stefan-Boltzmann law in solar units is

LL⊙=(RR⊙)2(T5772 K)4\frac{L}{L_\odot} = \left(\frac{R}{R_\odot}\right)^2 \left(\frac{T}{5772\ \text{K}}\right)^4

so stars of equal radius lie on straight diagonal lines on a log-log HR diagram (the dashed lines above). Moving up at a fixed temperature means a bigger star; moving left at a fixed luminosity means a smaller, hotter one. Giants, cool and yet luminous, must therefore be enormous, and white dwarfs, hot and yet faint, must be tiny.

About 90% of the stars near the Sun are on the main sequence, according to the OpenStax Astronomy textbook. Red dwarfs are by far the most common. Giants are rare nearby, but they are so luminous that they are over-represented in any catalogue limited by brightness.

Spectral classes: O B A F G K M​

Astronomers sort stars by the absorption lines in their spectra, and the classes follow temperature. Each class is split into ten subclasses, 0 (hottest) to 9; the Sun is G2.

ClassColourApproximate surface temperatureStrongest lines
OBlueAbove 30,000 KIonised helium
BBlue-white10,000 to 30,000 KNeutral helium, hydrogen growing
AWhite7,500 to 10,000 KHydrogen at its strongest
FYellow-white6,000 to 7,500 KHydrogen weaker, ionised calcium
GYellow5,200 to 6,000 KIonised calcium, metals
KOrange3,700 to 5,200 KNeutral metals
MRed2,400 to 3,700 KMolecules, mainly titanium oxide

Below M come L, T and Y, mostly brown dwarfs, too small to sustain hydrogen fusion. A second label, the luminosity class, says which region a star is in: I for supergiants, II for bright giants, III for giants, IV for subgiants and V for main-sequence stars. The Sun's full type, G2V, reads as a yellow main-sequence star, a little cooler than the hottest G stars.

How to read an HR diagram​

Read an HR diagram by checking the axes first, then finding the main sequence and placing each star relative to it.

  1. Read the axis labels. Is the horizontal axis temperature, colour index or spectral class? Is the vertical axis luminosity or absolute magnitude? Check which way each one runs: magnitude axes are brightest at the top, with the most negative numbers there.
  2. Check the scales. On a log luminosity axis, each gridline is usually ten times the one below. On a magnitude axis, 5 magnitudes is a factor of 100.
  3. Find the main sequence, the densest diagonal band. A star on it is in the hydrogen-burning stage, and its position along the band gives its mass: higher and further left means more massive.
  4. Place the star you're interested in. Above the main sequence at the same temperature means larger and more evolved: a subgiant, giant or supergiant. Below and to the left means a white dwarf.
  5. Read off its temperature and luminosity, and work out its radius from the Stefan-Boltzmann law if you need it.
  6. For a star cluster, find where the main sequence ends at the top (the turn-off), and use it to estimate the age (see below).

Worked example: the radius of a white dwarf​

The white dwarf 40 Eridani B has a surface temperature of about 17,200 K and a luminosity of about 0.0135 times the Sun's. On an HR diagram it sits well below the main sequence, at the left. Its radius is

RR⊙=LL⊙(5772 KT)2=0.0135×(577217200)2≈0.116×0.113≈0.013\frac{R}{R_\odot} = \sqrt{\frac{L}{L_\odot}}\left(\frac{5772\ \text{K}}{T}\right)^2 = \sqrt{0.0135}\times\left(\frac{5772}{17200}\right)^2 \approx 0.116 \times 0.113 \approx 0.013

That is about 1.3% of the Sun's radius, or roughly 1.4 times the Earth's. By the same formula, a cool star at 3,600 K with 50,000 times the Sun's luminosity has a radius of about 570 Suns: a red supergiant that, in place of the Sun, would reach beyond the orbit of Mars.

How a star moves across the HR diagram​

A star stays at nearly the same spot on the main sequence for most of its life, then leaves it. The main stages for a star like the Sun are:

  • Main sequence: hydrogen fuses into helium in the core. The star brightens slowly: the Sun roughly doubles in brightness over its main-sequence life of about 10 billion years.
  • Subgiant and red giant: when the core runs out of hydrogen, fusion moves to a shell around it. The envelope swells and cools, and the star moves right and then up the red giant branch.
  • Helium burning: helium ignites in the core and the star settles, for a time, into the red clump (for stars like the Sun) or a horizontal branch.
  • White dwarf: the outer layers drift off as a planetary nebula, and the exposed core drops to the lower left and cools for billions of years.

Stars above about 8 solar masses run through the same stages far faster, cross the top of the diagram as supergiants, and end as supernovae, leaving neutron stars or black holes that don't appear on the diagram. Before the main sequence, young stars contract onto it from the right.

Colour-magnitude diagrams of star clusters​

A colour-magnitude diagram (CMD) is an HR diagram in observed units: colour index against magnitude. It is the standard way to plot a star cluster. All the cluster's stars are at about the same distance, so their apparent magnitudes can be compared directly, without knowing each star's distance; and they formed at about the same time from the same gas.

The massive stars use up their hydrogen first, so a cluster's main sequence is eaten away from the top as it ages. The point where the remaining main sequence bends off towards the giants is the main-sequence turn-off, and the lower it is, the older the cluster. A rough rule, from main-sequence lifetimes, gives the turn-off mass for an age:

tMS≈10 billion years×(MM⊙)−2.5t_\text{MS} \approx 10\ \text{billion years} \times \left(\frac{M}{M_\odot}\right)^{-2.5}
Cluster ageTurn-off mass (rough rule)Turn-off spectral type, roughlyWhat the CMD looks like
10 million yearsAbout 16 solar massesEarly BAlmost the whole main sequence, a few red supergiants
100 million yearsAbout 6 solar massesMid BUpper main sequence gone, a handful of giants
1 billion yearsAbout 2.5 solar massesLate B to early ATurn-off near A stars, a clump of red giants
5 billion yearsAbout 1.3 solar massesFTurn-off just above the Sun, subgiant and giant branches
10 billion yearsAbout 1 solar massGTurn-off at the Sun's position, as in globular clusters

In practice astronomers fit isochrones, model curves for stars of one age and composition, to the whole CMD, and the turn-off is the part that fixes the age most tightly. Globular clusters come out at about 11 billion years or older. Distance shifts the whole diagram up or down, and dust makes stars both fainter and redder, so both are fitted at the same time.

HR diagram vs colour-magnitude diagram vs spectral-class diagram​

The theoretical HR diagram, the colour-magnitude diagram and the spectral-class diagram show the same pattern of stars with different quantities on the axes.

VersionAxesChoose it when
Theoretical HR diagramlog⁡T\log T against log⁡L/L⊙\log L/L_\odotYou're comparing with models or evolution tracks, or showing radius lines
Colour-magnitude diagramColour index against absolute or apparent magnitudeYou're plotting survey or cluster photometry as measured
Spectral-class diagramSpectral class against absolute magnitude or luminosityYou're teaching, or the stars were classified from spectra rather than photometry
Density HR diagram (heatmap)Either of the above, coloured by star count per cellYou have hundreds of thousands of stars and the points overlap, as in Gaia plots

Large surveys now use the CMD. ESA's Hipparcos satellite, launched in 1989, measured precise positions and parallaxes (distances) for 118,218 stars, giving the first HR diagram with accurate distances for a large sample. ESA's Gaia mission has since measured parallaxes for more than a billion stars (Data Release 3, 2022), plotted as colour BP-RP against absolute magnitude MGM_G, and its HR diagram is thin enough to show features such as two separate white dwarf sequences.

Common HR diagram mistakes​

The commonest HR diagram mistakes come from its unusual axes: temperature that falls to the right and magnitudes that are smaller for brighter stars.

  • Reading the temperature axis as rising to the right. Temperature falls from left to right, with the hottest stars on the left. Label the axis, or add an arrow, when you draw one.
  • Reading the magnitude scale the wrong way up. On a magnitude axis smaller numbers are brighter, and the top of the axis carries the most negative values. A star at MV=−5M_V = -5 is about 10,000 times more luminous than one at MV=+5M_V = +5.
  • Mixing apparent and absolute magnitude. Apparent magnitude depends on distance: the Sun's is -26.74, its absolute magnitude +4.83. Field stars at different distances only make an HR diagram after converting to absolute magnitude; a cluster CMD can use apparent magnitude because all its stars are at about the same distance.
  • Treating the main sequence as an evolutionary track. Stars don't slide down it as they age. Their place on it is set by mass.
  • Ignoring dust. Interstellar dust dims and reddens starlight, moving stars down and to the right. Correct for it before comparing a distant cluster with nearby stars.
  • Drawing it on linear axes. Without log scales almost every star is crushed against the bottom.
  • Overplotting. With tens of thousands of stars, points hide each other and the densest parts look no busier than the rest. Use smaller, semi-transparent points or a density heatmap.

How to plot an HR diagram in JavaScript, React or Angular​

Star catalogues are large: Gaia's holds over a billion sources, and even a cleaned sample for an HR diagram runs to hundreds of thousands of stars. The demo below plots 9,000 simulated field stars or an 8,000-star cluster, placed with textbook relations rather than taken from a real catalogue, and switches the same data between a scatter series and a density heatmap. For catalogue-sized data, the one-million-point performance demo shows how SciChart.js handles a million points on your own device.

Use Stars to switch between stars near the Sun and a star cluster, then drag Cluster age from 10 million to over 12 billion years and watch the turn-off slide down the main sequence. Axes switches between temperature and luminosity and colour index and absolute magnitude, and View between points and a density heatmap. Regions and classes labels the regions and spectral classes, Radius lines draws stars of equal radius, and The Sun marks it. Hover over a star for its temperature, luminosity, colour, magnitude, radius and spectral type; scroll to zoom, drag to pan and double-click to reset.

Here is the code for this chart. The star simulation and unit conversions are plain JavaScript; SciChart.js draws the stars, the heatmap, the radius lines and the labels. The React and Angular versions show a plain HR diagram on logarithmic axes.

// A Hertzsprung-Russell diagram: stars plotted by temperature (reversed, log scale) and luminosity (log scale),
// or by colour index and absolute magnitude, coloured by temperature, as points or as a density heatmap
const {
SciChartSurface,
NumericAxis,
NumberRange,
NumericTickProvider,
XyDataSeries,
XyScatterRenderableSeries,
FastLineRenderableSeries,
EllipsePointMarker,
MetadataPaletteProvider,
UniformHeatmapDataSeries,
UniformHeatmapRenderableSeries,
HeatmapColorMap,
TextAnnotation,
VerticalLineAnnotation,
ECoordinateMode,
EAxisAlignment,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
Thickness,
DpiHelper,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// Both kinds of HR diagram, as functions from a star's temperature (K) and luminosity (Suns) to chart x and y.
// The axes hold log10 values; the tick and label functions below show them as kelvin and Suns.
const AXES = {
physical: {
x: (t) => Math.log10(t),
y: (t, l) => Math.log10(l),
xRange: new NumberRange(3.38, 4.7),
yRange: new NumberRange(-4.6, 6.4),
xTitle: "Surface temperature (K), hotter to the left",
yTitle: "Luminosity (Sun = 1)",
flipX: true, // temperature falls from left to right
flipY: false,
xTicks: [2500, 3000, 4000, 5000, 6000, 8000, 10000, 15000, 20000, 30000, 40000].map(Math.log10),
yTicks: [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6],
xLabel: (v) => Math.round(10 ** v / 100) * 100 + " K",
yLabel: (v) => (v >= 0 ? (10 ** v).toLocaleString("en-GB", { maximumFractionDigits: 0 }) : String(+(10 ** v).toPrecision(1)))
},
observed: {
x: (t) => colourIndex(t),
y: (t, l) => absoluteMagnitude(t, l),
xRange: new NumberRange(-0.45, 2.15),
yRange: new NumberRange(-9, 17),
xTitle: "Colour index B-V (bluer to the left)",
yTitle: "Absolute magnitude M_V (brighter is up)",
flipX: false,
flipY: true, // smaller magnitudes are brighter, so they go at the top
xTicks: null, // automatic ticks
yTicks: null,
xLabel: (v) => v.toFixed(1),
yLabel: (v) => v.toFixed(0)
}
};

const { sciChartSurface, wasmContext } = await SciChartSurface.create(ui.chartDiv, {
theme: new SciChartJsNavyTheme()
});
const xAxis = new NumericAxis(wasmContext, { axisTitle: "", drawMinorGridLines: false });
const yAxis = new NumericAxis(wasmContext, { axisTitle: "", drawMinorGridLines: false, axisAlignment: EAxisAlignment.Left });
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);

// Ticks at round temperatures and powers of ten (log mode), or SciChart's automatic ticks (magnitude mode)
let axes = AXES.physical;
for (const { axis, key } of [{ axis: xAxis, key: "xTicks" }, { axis: yAxis, key: "yTicks" }]) {
const ticks = new NumericTickProvider(wasmContext);
const automatic = ticks.getMajorTicks.bind(ticks);
ticks.getMajorTicks = (minorDelta, majorDelta, range) =>
axes[key] ? axes[key].filter((v) => v >= range.min && v <= range.max) : automatic(minorDelta, majorDelta, range);
axis.tickProvider = ticks;
}
xAxis.labelProvider.formatLabel = (v) => axes.xLabel(v);
yAxis.labelProvider.formatLabel = (v) => axes.yLabel(v);

// Density view: stars counted on a grid; empty cells are transparent
const GRID_X = 120;
const GRID_Y = 90;
const heatmapData = new UniformHeatmapDataSeries(wasmContext, {
zValues: Array.from({ length: GRID_Y }, () => new Array(GRID_X).fill(0)),
xStart: 0,
xStep: 1,
yStart: 0,
yStep: 1
});
const heatmap = new UniformHeatmapRenderableSeries(wasmContext, {
dataSeries: heatmapData,
colorMap: new HeatmapColorMap({
minimum: 0,
maximum: 1,
gradientStops: [
{ offset: 0, color: "#00000000" },
{ offset: 0.001, color: "#1B2E6B" },
{ offset: 0.3, color: "#2F7FC1" },
{ offset: 0.6, color: "#50C7E0" },
{ offset: 0.85, color: "#F5E663" },
{ offset: 1, color: "#FFFFFF" }
]
}),
isVisible: false
});

// Points view: one scatter series; each point's colour comes from its metadata (MetadataPaletteProvider)
const starData = new XyDataSeries(wasmContext, { dataSeriesName: "Stars" });
const stars = new XyScatterRenderableSeries(wasmContext, {
dataSeries: starData,
pointMarker: new EllipsePointMarker(wasmContext, { width: 4, height: 4, strokeThickness: 0, fill: "#FFFFFF" }),
paletteProvider: new MetadataPaletteProvider()
});

// Lines of constant radius (Stefan-Boltzmann law), the Sun, the cluster turn-off and the star under the mouse
const RADII = [0.01, 0.1, 1, 10, 100, 1000];
const radiusData = RADII.map((r) => new XyDataSeries(wasmContext, { dataSeriesName: `${r} solar radii` }));
const radiusLines = radiusData.map(
(dataSeries) =>
new FastLineRenderableSeries(wasmContext, {
dataSeries,
stroke: "#C8D3E8",
strokeThickness: 1,
strokeDashArray: [4, 4],
opacity: 0.6
})
);
const sunData = new XyDataSeries(wasmContext, { dataSeriesName: "Sun" });
const turnOffData = new XyDataSeries(wasmContext, { dataSeriesName: "Turn-off" });
const hoveredData = new XyDataSeries(wasmContext, { dataSeriesName: "Hovered star" });
const marker = (dataSeries, fill, stroke, size) =>
new XyScatterRenderableSeries(wasmContext, {
dataSeries,
pointMarker: new EllipsePointMarker(wasmContext, { width: size, height: size, strokeThickness: 2, fill, stroke })
});
const sun = marker(sunData, "#FFD84D", "#FFFFFF", 14);
const turnOff = marker(turnOffData, "#00000000", "#F48420", 22);
const hovered = marker(hoveredData, "#00000000", "#FFFFFF", 14);
sciChartSurface.renderableSeries.add(heatmap, ...radiusLines, stars, sun, turnOff, hovered);
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier());

// --- Redraw everything for the current controls ---
const fieldStars = simulateFieldStars(9000);
const cluster = createCluster(8000);
let current = [];
let points = { x: [], y: [] };

function update() {
axes = AXES[ui.axesSelect.value];
const isCluster = ui.starsSelect.value === "cluster";
const ageGyr = 10 ** (Number(ui.ageInput.value) - 9);
ui.ageInput.disabled = !isCluster;
ui.ageOutput.textContent = ageGyr < 1 ? `${Math.round(ageGyr * 1000)} million years` : `${ageGyr.toFixed(1)} billion years`;
current = isCluster ? cluster(ageGyr) : fieldStars;

// Axes
xAxis.labelProvider.invalidateCache(); // the label text for a value changes with the mode
yAxis.labelProvider.invalidateCache();
xAxis.axisTitle = axes.xTitle;
yAxis.axisTitle = axes.yTitle;
xAxis.flippedCoordinates = axes.flipX;
yAxis.flippedCoordinates = axes.flipY;
xAxis.visibleRange = axes.xRange;
yAxis.visibleRange = axes.yRange;
xAxis.visibleRangeLimit = axes.xRange;
yAxis.visibleRangeLimit = axes.yRange;

// Stars
points = {
x: current.map((s) => axes.x(s.temperature)),
y: current.map((s) => axes.y(s.temperature, s.luminosity))
};
const metadata = current.map((s) => {
const colour = starColour(s.temperature);
return { isSelected: false, fill: colour + "CC", stroke: colour };
});
starData.clear();
starData.appendRange(points.x, points.y, metadata);
hoveredData.clear();
ui.tooltip.style.display = "none";

// Density: count stars per grid cell, on a log scale so sparse regions still show
const density = ui.viewSelect.value === "density";
const { xRange, yRange } = axes;
const xStep = (xRange.max - xRange.min) / GRID_X;
const yStep = (yRange.max - yRange.min) / GRID_Y;
const counts = Array.from({ length: GRID_Y }, () => new Array(GRID_X).fill(0));
points.x.forEach((x, i) => {
const col = Math.floor((x - xRange.min) / xStep);
const row = Math.floor((points.y[i] - yRange.min) / yStep);
if (col >= 0 && col < GRID_X && row >= 0 && row < GRID_Y) counts[row][col]++;
});
const peak = Math.log10(1 + Math.max(...counts.map((row) => Math.max(...row))));
heatmapData.xStart = xRange.min;
heatmapData.xStep = xStep;
heatmapData.yStart = yRange.min;
heatmapData.yStep = yStep;
heatmapData.setZValues(counts.map((row) => row.map((n) => (n ? Math.max(0.01, Math.log10(1 + n) / peak) : 0))));
heatmap.isVisible = density;
stars.isVisible = !density;

// Radius lines: L = R^2 (T / T_sun)^4, drawn across the temperature range
radiusLines.forEach((line, i) => {
const xs = [];
const ys = [];
for (let logT = 3.38; logT <= 4.7; logT += 0.02) {
const t = 10 ** logT;
xs.push(axes.x(t));
ys.push(axes.y(t, RADII[i] ** 2 * (t / SUN_TEMPERATURE) ** 4));
}
radiusData[i].clear();
radiusData[i].appendRange(xs, ys);
line.isVisible = ui.radiiCheckbox.checked;
});

// The Sun
sunData.clear();
sunData.append(axes.x(SUN_TEMPERATURE), axes.y(SUN_TEMPERATURE, 1));
sun.isVisible = ui.sunCheckbox.checked;

// The cluster's main-sequence turn-off: the most massive star still burning hydrogen in its core
turnOffData.clear();
turnOff.isVisible = isCluster;
let turnOffText = "";
if (isCluster) {
const remaining = current.filter((s) => s.stage === "Main sequence");
const top = remaining.reduce((a, b) => (b.luminosity > a.luminosity ? b : a), remaining[0]);
turnOffData.append(axes.x(top.temperature), axes.y(top.temperature, top.luminosity));
turnOffText = ` · turn-off at about ${top.mass.toFixed(1)} solar masses, ${Math.round(top.temperature / 100) * 100} K`;
}

// Labels: spectral classes along the top, the main regions, the Sun, the turn-off and the radius lines
sciChartSurface.annotations.clear();
const label = (x, y, text, options) =>
sciChartSurface.annotations.add(
new TextAnnotation({
x1: x,
y1: y,
text,
fontSize: 14,
textColor: "#FFFFFF",
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Center,
...options
})
);
if (ui.regionsCheckbox.checked) {
for (const c of SPECTRAL_CLASSES) {
const mid = Math.sqrt(c.from * Math.max(c.to, 2600));
label(axes.x(mid), 0.03, c.letter, { yCoordinateMode: ECoordinateMode.Relative, fontSize: 16, textColor: starColour(mid) });
if (c.to > 2600) {
sciChartSurface.annotations.add(
new VerticalLineAnnotation({ x1: axes.x(c.to), stroke: "#C8D3E855", strokeDashArray: [2, 4] })
);
}
}
const regions = isCluster
? []
: [
{ text: "Main sequence", t: 16000, l: 30 },
{ text: "Giants", t: 4200, l: 600 },
{ text: "Supergiants", t: 6500, l: 6000 },
{ text: "White dwarfs", t: 16000, l: 0.0006 }
];
for (const r of regions) {
label(axes.x(r.t), axes.y(r.t, r.l), r.text, { fontSize: 15, background: "#22365BCC", padding: new Thickness(2, 4, 2, 4) });
}
}
if (ui.radiiCheckbox.checked) {
RADII.forEach((r) => {
// Label each line at its coolest point inside the chart
const lumAt = (t) => r * r * (t / SUN_TEMPERATURE) ** 4;
let t = 2700;
while (t < 40000 && Math.log10(lumAt(t)) < AXES.physical.yRange.min + 0.5) t *= 1.05;
label(axes.x(t), axes.y(t, lumAt(t)), `${r} R☉`, { fontSize: 12, textColor: "#C8D3E8" });
});
}
if (ui.sunCheckbox.checked) {
label(axes.x(SUN_TEMPERATURE), axes.y(SUN_TEMPERATURE, 1), "Sun", {
horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
verticalAnchorPoint: EVerticalAnchorPoint.Top,
xCoordShift: 6,
yCoordShift: 6,
background: "#22365BCC",
textColor: "#FFD84D"
});
}
if (isCluster) {
const p = turnOffData;
label(p.getNativeXValues().get(0), p.getNativeYValues().get(0), "Turn-off", {
horizontalAnchorPoint: EHorizontalAnchorPoint.Right,
xCoordShift: -14,
textColor: "#F48420"
});
}

// One-line summary of what is plotted
const giants = current.filter((s) => /giant/i.test(s.stage)).length;
const dwarfs = current.filter((s) => s.stage === "White dwarf").length;
ui.summary.textContent =
`${current.length.toLocaleString("en-GB")} simulated stars · ` +
`${Math.round((100 * (current.length - giants - dwarfs)) / current.length)}% main sequence or subgiant, ` +
`${giants} giants, ${dwarfs} white dwarfs` +
turnOffText;
}

// --- Hover: find the nearest star on screen and show its values ---
ui.chartDiv.addEventListener("mousemove", (event) => {
if (!stars.isVisible || current.length === 0) return;
const box = ui.chartDiv.getBoundingClientRect();
const view = sciChartSurface.seriesViewRect;
const mouseX = (event.clientX - box.left) * DpiHelper.PIXEL_RATIO - view.left;
const mouseY = (event.clientY - box.top) * DpiHelper.PIXEL_RATIO - view.top;
const xCalc = xAxis.getCurrentCoordinateCalculator();
const yCalc = yAxis.getCurrentCoordinateCalculator();
let best = -1;
let bestDistance = (10 * DpiHelper.PIXEL_RATIO) ** 2;
for (let i = 0; i < current.length; i++) {
const dx = xCalc.getCoordinate(points.x[i]) - mouseX;
const dy = yCalc.getCoordinate(points.y[i]) - mouseY;
if (dx * dx + dy * dy < bestDistance) {
bestDistance = dx * dx + dy * dy;
best = i;
}
}
hoveredData.clear();
if (best < 0) {
ui.tooltip.style.display = "none";
return;
}
hoveredData.append(points.x[best], points.y[best]);
const s = current[best];
const lum = s.luminosity >= 1 ? s.luminosity.toLocaleString("en-GB", { maximumFractionDigits: 1 }) : s.luminosity.toPrecision(2);
ui.tooltip.innerHTML =
`<b>${s.stage}</b>, spectral type about ${spectralType(s.temperature)}<br>` +
`Temperature ${Math.round(s.temperature).toLocaleString("en-GB")} K · luminosity ${lum} Suns<br>` +
`B-V ${colourIndex(s.temperature).toFixed(2)} · M<sub>V</sub> ${absoluteMagnitude(s.temperature, s.luminosity).toFixed(1)} · ` +
`radius ${+radiusOf(s.temperature, s.luminosity).toPrecision(2)} Suns` +
(s.mass ? ` · mass ${s.mass.toFixed(2)} Suns` : "");
const cssX = event.clientX - box.left;
const cssY = event.clientY - box.top;
ui.tooltip.style.display = "block";
ui.tooltip.style.left = `${Math.min(cssX + 14, box.width - ui.tooltip.offsetWidth - 4)}px`;
ui.tooltip.style.top = `${cssY > box.height / 2 ? cssY - ui.tooltip.offsetHeight - 10 : cssY + 14}px`;
});
ui.chartDiv.addEventListener("mouseleave", () => {
ui.tooltip.style.display = "none";
hoveredData.clear();
});

ui.starsSelect.addEventListener("change", update);
ui.ageInput.addEventListener("input", update);
ui.axesSelect.addEventListener("change", update);
ui.viewSelect.addEventListener("change", update);
ui.regionsCheckbox.addEventListener("change", update);
ui.radiiCheckbox.addEventListener("change", update);
ui.sunCheckbox.addEventListener("change", update);
update();

Key points:

  • The stars are one XyScatterRenderableSeries. A MetadataPaletteProvider colours each point from the fill and stroke in its metadata, here the approximate blackbody colour of the star's temperature.
  • For a plain HR diagram, as in the React and Angular code, use two LogarithmicAxis objects and set flippedCoordinates: true on the temperature axis. The live demo plots log values on NumericAxis objects instead, with a custom tick provider and labelProvider.formatLabel, so it can switch the same axes to colour index and magnitude.
  • Absolute magnitude gets smaller as stars get brighter, so the magnitude view flips the y-axis with flippedCoordinates.
  • The density view counts stars on a grid and draws the counts with a UniformHeatmapRenderableSeries on the same axes. Radius lines are FastLineRenderableSeries, and labels are TextAnnotations.

See it in the demo app: JavaScript scatter chart · React scatter chart · Angular scatter chart; for density, JavaScript heatmap chart · React heatmap chart · Angular heatmap chart; and for very large point counts, JavaScript chart with one million points · React chart with one million points · Angular chart with one million points.

Go deeper: SciChart.js scatter series documentation, the uniform heatmap documentation and the guides to the scatter plot and density plot. For how instrument makers and research teams use SciChart for scientific data, see SciChart for instrumentation software.

Frequently asked questions​

What does an HR diagram show?​

An HR diagram shows how bright stars really are against how hot their surfaces are. Each star is one point: luminosity or absolute magnitude on the vertical axis, and surface temperature, colour index or spectral class on the horizontal axis. Stars fall into groups rather than scattering at random, and each group is a stage of a star's life: the main sequence, giants, supergiants and white dwarfs.

Why does temperature decrease to the right on an HR diagram?​

The first HR diagrams plotted spectral class, and the classes were ordered O, B, A, F, G, K, M from left to right. That order turned out to run from hottest to coolest, so when temperature replaced spectral class the axis kept the same direction. Hot blue stars sit on the left and cool red stars on the right.

Where is the Sun on the HR diagram?​

The Sun is on the main sequence, near its middle: a surface temperature of 5,772 K and a luminosity of 1 in solar units, by definition. On the observer's version it has a colour index B-V of about 0.65 and an absolute visual magnitude of 4.83. Its spectral type is G2V, where V means a main-sequence star.

What is the main sequence on an HR diagram?​

The main sequence is the diagonal band from hot, bright stars at the top left to cool, dim stars at the bottom right. Its stars fuse hydrogen into helium in their cores, the longest stage of a star's life, so most stars are found there. A star's place along the band is set mainly by its mass: the most massive are at the top left.

How do you find the age of a star cluster from its HR diagram?​

Find the turn-off, the point where the cluster's main sequence stops and bends towards the giants. All the stars formed at about the same time, and the most massive ones leave the main sequence first. The mass of the stars at the turn-off gives the age: a main-sequence lifetime of roughly 10 billion years times mass to the power of minus 2.5, with mass in solar masses. Astronomers fit model isochrones for a precise age.

How do I plot an HR diagram in JavaScript?​

Put the stars in a scatter series with temperature on the x-axis and luminosity on the y-axis, both on logarithmic axes, and flip the x-axis so temperature falls from left to right. Colour each point by temperature with a per-point palette, and add zoom, pan and a hover readout. For hundreds of thousands of stars, use a charting library that draws with WebGL and WebGPU, such as SciChart.js, or show the density as a heatmap.

Sources​