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, coloured by temperature, with the main regions and spectral classes labelled. Try the interactive version.
- 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 diagram | Observer's HR diagram (colour-magnitude diagram) | |
|---|---|---|
| Horizontal axis | Surface (effective) temperature in kelvin, log scale, hotter to the left | Colour index, such as B-V or Gaia's BP-RP; bluer (hotter) to the left |
| Vertical axis | Luminosity in solar units (), log scale | Absolute magnitude, such as ; brighter is up, so the numbers fall upwards |
| Comes from | Models, or measurements converted to physical units | Two brightness measurements and a distance |
| Used for | Stellar evolution tracks, comparing with theory | Star 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 () 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 (), how bright the star looks from Earth, and its distance :
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.
| Region | Where on the diagram | Typical temperature | Typical luminosity (Sun = 1) | What the stars are doing |
|---|---|---|---|---|
| Main sequence | Diagonal band, top left to bottom right | About 2,500 K to over 40,000 K | About 0.001 to 1,000,000 | Fusing hydrogen into helium in the core |
| Subgiants | Just above the main sequence, between it and the giants | About 5,000 K to 6,500 K | About 2 to 10 | Core hydrogen used up; the star starts to swell |
| Red giants | Upper right | About 3,500 K to 5,200 K | About 10 to 3,000 | Hydrogen burning in a shell round a helium core, or helium burning in the core (the red clump) |
| Supergiants | Across the top | Any, from red (3,500 K) to blue (30,000 K) | About 10,000 to 1,000,000 | Massive stars in their late stages |
| White dwarfs | Lower left | About 5,000 K to over 30,000 K | About 0.0001 to 0.1 | Burnt-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
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.
| Class | Colour | Approximate surface temperature | Strongest lines |
|---|---|---|---|
| O | Blue | Above 30,000 K | Ionised helium |
| B | Blue-white | 10,000 to 30,000 K | Neutral helium, hydrogen growing |
| A | White | 7,500 to 10,000 K | Hydrogen at its strongest |
| F | Yellow-white | 6,000 to 7,500 K | Hydrogen weaker, ionised calcium |
| G | Yellow | 5,200 to 6,000 K | Ionised calcium, metals |
| K | Orange | 3,700 to 5,200 K | Neutral metals |
| M | Red | 2,400 to 3,700 K | Molecules, 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.
- 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.
- 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.
- 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.
- 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.
- Read off its temperature and luminosity, and work out its radius from the Stefan-Boltzmann law if you need it.
- 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
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:
| Cluster age | Turn-off mass (rough rule) | Turn-off spectral type, roughly | What the CMD looks like |
|---|---|---|---|
| 10 million years | About 16 solar masses | Early B | Almost the whole main sequence, a few red supergiants |
| 100 million years | About 6 solar masses | Mid B | Upper main sequence gone, a handful of giants |
| 1 billion years | About 2.5 solar masses | Late B to early A | Turn-off near A stars, a clump of red giants |
| 5 billion years | About 1.3 solar masses | F | Turn-off just above the Sun, subgiant and giant branches |
| 10 billion years | About 1 solar mass | G | Turn-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.
| Version | Axes | Choose it when |
|---|---|---|
| Theoretical HR diagram | against | You're comparing with models or evolution tracks, or showing radius lines |
| Colour-magnitude diagram | Colour index against absolute or apparent magnitude | You're plotting survey or cluster photometry as measured |
| Spectral-class diagram | Spectral class against absolute magnitude or luminosity | You'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 cell | You 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 , 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 is about 10,000 times more luminous than one at .
- 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.
- JavaScript
- React
- Angular
// 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();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
LogarithmicAxis,
NumberRange,
ENumericFormat,
EAxisAlignment,
XyDataSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
MetadataPaletteProvider,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// Temperature on a log axis, flipped so the hottest stars are on the left
sciChartSurface.xAxes.add(
new LogarithmicAxis(wasmContext, {
axisTitle: "Surface temperature (K)",
logBase: 10,
flippedCoordinates: true,
visibleRange: new NumberRange(2500, 40000),
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 2
})
);
// Luminosity in solar units on a log axis
sciChartSurface.yAxes.add(
new LogarithmicAxis(wasmContext, {
axisTitle: "Luminosity (Sun = 1)",
axisAlignment: EAxisAlignment.Left,
logBase: 10,
visibleRange: new NumberRange(1e-4, 1e6),
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 1
})
);
// Your stars: temperature (K), luminosity (Sun = 1) and a colour for each, e.g. from its temperature
const { temperatures, luminosities, colours } = getYourStarData();
const metadata = colours.map((colour) => ({ isSelected: false, fill: colour, stroke: colour }));
sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: temperatures, yValues: luminosities, metadata }),
pointMarker: new EllipsePointMarker(wasmContext, { width: 4, height: 4, strokeThickness: 0 }),
paletteProvider: new MetadataPaletteProvider() // each point takes its colour from its metadata
})
);
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier());
return { sciChartSurface };
};
export const HrDiagram = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 500 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
LogarithmicAxis,
NumberRange,
ENumericFormat,
EAxisAlignment,
XyDataSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
MetadataPaletteProvider,
SciChartJsNavyTheme,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
@Component({
selector: "app-hr-diagram",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 500px"></scichart-angular>`
})
export class HrDiagramComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
// Temperature on a log axis, flipped so the hottest stars are on the left
sciChartSurface.xAxes.add(
new LogarithmicAxis(wasmContext, {
axisTitle: "Surface temperature (K)",
logBase: 10,
flippedCoordinates: true,
visibleRange: new NumberRange(2500, 40000),
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 2
})
);
// Luminosity in solar units on a log axis
sciChartSurface.yAxes.add(
new LogarithmicAxis(wasmContext, {
axisTitle: "Luminosity (Sun = 1)",
axisAlignment: EAxisAlignment.Left,
logBase: 10,
visibleRange: new NumberRange(1e-4, 1e6),
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 1
})
);
// Your stars: temperature (K), luminosity (Sun = 1) and a colour for each, e.g. from its temperature
const { temperatures, luminosities, colours } = getYourStarData();
const metadata = colours.map((colour) => ({ isSelected: false, fill: colour, stroke: colour }));
sciChartSurface.renderableSeries.add(
new XyScatterRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: temperatures, yValues: luminosities, metadata }),
pointMarker: new EllipsePointMarker(wasmContext, { width: 4, height: 4, strokeThickness: 0 }),
paletteProvider: new MetadataPaletteProvider() // each point takes its colour from its metadata
})
);
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier());
return { sciChartSurface };
};
}
Key points:
- The stars are one
XyScatterRenderableSeries. AMetadataPaletteProvidercolours each point from thefillandstrokein 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
LogarithmicAxisobjects and setflippedCoordinates: trueon the temperature axis. The live demo plots log values onNumericAxisobjects instead, with a custom tick provider andlabelProvider.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
UniformHeatmapRenderableSerieson the same axes. Radius lines areFastLineRenderableSeries, and labels areTextAnnotations.
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
- Fraknoi, A., Morrison, D. and Wolff, S. C., Astronomy 2e, OpenStax (2022, CC BY 4.0): 17.3 The spectra of stars (and brown dwarfs) for the spectral classes and temperatures; 18.4 The H–R diagram for its history, regions, and the share of main-sequence stars; 22.1 Evolution from the main sequence to red giants and 22.3 Checking out the theory for stellar evolution and cluster turn-offs.
- NASA Goddard Space Flight Center, Sun fact sheet: the Sun's effective temperature, luminosity, apparent and absolute visual magnitude and spectral type.
- International Astronomical Union (2015), Resolution B3 on nominal solar values (5,772 K, 3.828 × 10²⁶ W) and Resolution B2 on the bolometric magnitude scale (the Sun's absolute bolometric magnitude, 4.74).
- European Space Agency, Hipparcos (118,218 stars) and Gaia Data Release 2 HR diagrams; Gaia Collaboration, Babusiaux, C. et al. (2018), Gaia Data Release 2: Observational Hertzsprung-Russell diagrams, Astronomy & Astrophysics, 616, A10. Gaia Collaboration, Vallenari, A. et al. (2023), Gaia Data Release 3: Summary of the content and survey properties, Astronomy & Astrophysics, 674, A1.
- Bond, H. E., Bergeron, P. and Bédard, A. (2017), Astrophysical implications of a new dynamical mass for the nearby white dwarf 40 Eridani B, Astrophysical Journal, 848, 16: the temperature and luminosity of 40 Eridani B.
- Pecaut, M. J. and Mamajek, E. E. (2013), Intrinsic colors, temperatures, and bolometric corrections of pre-main-sequence stars, Astrophysical Journal Supplement, 208, 9, and its online table of main-sequence colours and temperatures: the colour-temperature relation in the demo. Torres, G. (2010), On the use of empirical bolometric corrections for stars, Astronomical Journal, 140, 1158: the bolometric corrections in the demo.