# Maxwell–Boltzmann speed distribution in pgfplots, explained

> How the Maxwell–Boltzmann speed distribution is plotted with pgfplots: a formula macro with tiny constants, siunitx labels, and two variations.

URL: https://www.labcanvas.com/tikz/examples/physics/maxwell-boltzmann-speed-distribution

Updated 2026-11-22. Original figure: Maxwell–Boltzmann speed distribution, © Janosh Riebesell and contributors, MIT licence (licence text: https://www.labcanvas.com/tikz-library/credits.html#janosh), from https://github.com/janosh/diagrams/blob/7a79b3114e201fad9b6785e936eab859d1bc8c12/assets/maxwell-boltzmann-distribution/maxwell-boltzmann-distribution.tex. Walkthrough and variations by LabCanvas; the variation code is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/). Pictures typeset with TeX Live 2026 and PGF 3.1.12. Category: [TikZ physics examples](https://www.labcanvas.com/tikz/examples/physics).

## Quick answer

This plot shows the Maxwell–Boltzmann distribution of molecular speeds at 100 K, 300 K and 1000 K: the curve flattens and its peak moves to higher speeds as the temperature rises. It is a pgfplots `axis` with three `\addplot` commands, each evaluating the same formula, written once as a TeX macro that takes the temperature as its argument. The constants are tiny (10 −23 and 10 −27), which works because pgfplots evaluates plot expressions with a floating-point unit, and the axis label and legend use siunitx for the units.

## The figure and its code

![Plot of P(v) against v in metres per second from 0 to 8,000: a tall narrow red curve for 100 K peaking near 1,300 m/s, a lower yellow curve for 300 K peaking near 2,200 m/s and a broad blue curve for 1000 K peaking near 4,100 m/s, with the y axis scaled by 10 to the minus 4 and a legend in the top right.](https://www.labcanvas.com/tikz-snippets/fig-maxwell-boltzmann-speed-distribution/original.webp)

Copyright (c) 2021 Janosh Riebesell, MIT licence (https://www.labcanvas.com/tikz-library/credits.html#janosh). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence, and the MIT licence asks that they stay with the code. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/physics/maxwell-boltzmann-speed-distribution

```latex
% Maxwell–Boltzmann speed distribution
% Source: https://github.com/janosh/diagrams/blob/7a79b3114e201fad9b6785e936eab859d1bc8c12/assets/maxwell-boltzmann-distribution/maxwell-boltzmann-distribution.tex
% Copyright (c) 2021 Janosh Riebesell. MIT licence: https://github.com/janosh/diagrams/blob/main/license
% The licence’s copyright and permission notice: https://www.labcanvas.com/tikz-library/credits.html
\documentclass{standalone}

\usepackage{pgfplots,siunitx}
\pgfplotsset{compat=newest}

\def\kB{1.38e-23} % Boltzmann constant
\def\mu{1.66e-27} % unified atomic mass unit/Dalton (symbols: m_u or Da)

\def\maxwellboltzmann#1{4 * pi * (\mu / (2 * pi * \kB * #1))^(3/2) * x^2 * exp(-\mu * x^2 / (2 * \kB * #1))}

\begin{document}

\begin{tikzpicture}

  \begin{axis}[
      domain = 0:8000,
      xlabel = {$v$ [\si{\metre\per\second}]},
      ylabel = $P(v)$,
      smooth, thick,
      axis lines = left,
      every tick/.style = {thick},
    ]

    \addplot[color=red,samples=100]{\maxwellboltzmann{100}};

    \addplot[color=yellow]{\maxwellboltzmann{300}};

    \addplot[color=blue]{\maxwellboltzmann{1000}};

    \legend{\SI{100}{\kelvin}, \SI{300}{\kelvin}, \SI{1000}{\kelvin}}

  \end{axis}
\end{tikzpicture}

\end{document}
```

## pgfplots, siunitx and compat=newest

*Lines 5–8 of the code.*

The plot needs two packages: `pgfplots`, which loads TikZ and provides the `axis` environment, and `siunitx` for the units. `\pgfplotsset{compat=newest}` asks for the newest behaviour of whichever pgfplots version compiles the file. That is convenient but means the plot can change after an update; a fixed value such as `compat=1.18`, as in the variations, keeps the output the same.

## Constants and the formula as a macro

*Lines 10–13 of the code.*

The Boltzmann constant and the mass are stored as plain text with `\def`: `\def\kB{1.38e-23}` and `\def\mu{1.66e-27}`, the atomic mass unit in kilograms. The curves are therefore for particles of mass 1 u, roughly hydrogen atoms. Note that `\mu` is also the Greek letter μ: after line 11, `$\mu$` anywhere in this document would print 1.66e-27. A name such as `\massu` avoids that.

`\def\maxwellboltzmann#1{…}` is a macro with one parameter, the temperature, which expands into a pgfplots expression in `x`: 4π (m / 2πk B T) 3/2 x² exp(−m x² / 2k B T), the Maxwell–Boltzmann density of speeds. Because the macro is expanded before pgfplots reads the expression, `\maxwellboltzmann{100}` is the formula with T = 100 written in. Numbers of order 10 −27 would overflow TikZ’s ordinary arithmetic, which stops at about ±16384, but `\addplot` expressions are evaluated with pgfplots’ floating-point unit, which handles them.

## The axis

*Lines 17–26 of the code.*

The options of the `axis` environment apply to every plot in it. `domain = 0:8000` sets the speeds that are sampled, `smooth` joins the samples with a curve instead of straight segments, and `thick` sets the line width. `axis lines = left` draws only the left and bottom axes, with arrow tips, instead of a full box, and `every tick/.style = {thick}` thickens the tick marks to match. The x label uses `\si{\metre\per\second}`, which siunitx prints as m s −1. pgfplots chooses the y ticks itself and, because the values are small, factors out the common 10 −4 at the top of the axis.

## Three curves and a legend

*Lines 28–34 of the code.*

Each `\addplot` evaluates the macro for one temperature. Only the first sets `samples=100`; the other two use the default of 25 samples, which is enough for the wide curves but would show corners on the narrow 100 K peak, the reason for the extra samples there. The colours are given explicitly: red, yellow and blue. Yellow on white is hard to read, on screen and especially in print, so the first variation uses a colour-blind-safe set with different dash patterns.

`\legend{…}` lists the entries in plot order, here with siunitx’s `\SI{100}{\kelvin}`. `\SI` and `\si` are the names from siunitx version 2; version 3 still accepts them, and calls them `\qty` and `\unit`.

## Techniques used

- [Function plots with pgfplots](https://www.labcanvas.com/tikz/plots): `\addplot` of an expression in `x` over a `domain`, with `samples` and `smooth`.
- [Units with siunitx](https://www.labcanvas.com/tikz/plots): `\si{\metre\per\second}` in the label and `\SI{100}{\kelvin}` in the legend.
- [Readable colours](https://www.labcanvas.com/tikz/colors): why yellow on white fails, and a colour-blind-safe cycle list instead.
- [Physics diagrams](https://www.labcanvas.com/tikz/physics-diagrams): distributions and other physics plots drawn with TikZ and pgfplots.

## Variations

Our own code, CC0 1.0, each typeset with TeX Live 2026 in a standalone document with the preamble lines shown.

### Readable colours, siunitx 3 and the most probable speed

The same three curves, written to avoid the tiny constants: with the most probable speed v p = √(2k B T/m), the density is f(v) = 4/√π · v²/v p ³ · exp(−v²/v p ²), declared once with `\pgfmathdeclarefunction{mb}{2}{…}` and called as `mb(x, 1289.5)`. A `cycle list` gives each curve a colour-blind-safe colour and its own dash pattern, the legend uses `\qty` from siunitx 3, and thin grey lines mark each v p, added with `forget plot` so they stay out of the legend.

![Plot of f(v) in seconds per metre against speed v in metres per second: a solid blue curve for 100 K, a dashed orange curve for 300 K and a dash-dotted teal curve for 1000 K, thin grey vertical lines from each peak to the axis, and the label v_p = sqrt(2 k_B T / m) at the first peak.](https://www.labcanvas.com/tikz-snippets/fig-maxwell-boltzmann-speed-distribution/most-probable-speed.webp)

*the distribution at 100, 300 and 1000 K for m = 1 u, with the most probable speeds marked*

Preamble: `\usepackage{tikz}`, `\usepackage{pgfplots}`, `\usepackage{siunitx}`, `\pgfplotsset{compat=1.18}`

```latex
\begin{tikzpicture}
  % f(v) written with the most probable speed vp = sqrt(2kT/m): no tiny constants
  \pgfmathdeclarefunction{mb}{2}{\pgfmathparse{4/sqrt(pi)*#1^2/#2^3*exp(-(#1/#2)^2)}}
  \begin{axis}[
      width=9cm, height=6cm, axis lines=left, ymin=0, ymax=7.8e-4,
      xtick={0,2000,...,8000},
      domain=0:8000, samples=120, smooth, no markers,
      xlabel={speed $v$ / \unit{\metre\per\second}},
      ylabel={$f(v)$ / \unit{\second\per\metre}},
      cycle list={{blue!70!black, very thick}, {orange!85!black, very thick, dashed},
                  {teal, very thick, dash dot}},
      legend cell align=left,
    ]
    % vp for m = 1 u: 1289.5, 2233.5 and 4077.9 m/s at 100, 300 and 1000 K
    \addplot {mb(x, 1289.5)};  \addlegendentry{\qty{100}{\kelvin}}
    \addplot {mb(x, 2233.5)};  \addlegendentry{\qty{300}{\kelvin}}
    \addplot {mb(x, 4077.9)};  \addlegendentry{\qty{1000}{\kelvin}}
    % the most probable speed of each curve, where f(vp) = 4/(e sqrt(pi) vp)
    \addplot[gray, thin, forget plot] coordinates {(1289.5,0) (1289.5,6.438e-4)};
    \addplot[gray, thin, forget plot] coordinates {(2233.5,0) (2233.5,3.717e-4)};
    \addplot[gray, thin, forget plot] coordinates {(4077.9,0) (4077.9,2.036e-4)};
    \node[font=\small, anchor=south west] at (axis cs:1289.5,6.438e-4) {$v_p = \sqrt{2k_BT/m}$};
  \end{axis}
\end{tikzpicture}
```

### One curve for every temperature

Measured in units of v p, all temperatures give the same curve, 4/√π · u² e −u². The shaded tail, an `\addplot` over `domain=2:3.5` closed down to the axis with `\closedcycle` and filled, is the share of particles faster than 2v p: erfc 2 + (4/√π) e −4 ≈ 4.6%. The filled plot is drawn first so that the curve lies on top of it.

![A single blue curve rising from zero to a peak of about 0.83 at u = 1, marked by a dashed vertical line and the label most probable speed, then falling towards zero by u = 3.5; the area under the curve beyond u = 2 is shaded orange and labelled 4.6 % of the particles are faster than 2 v_p.](https://www.labcanvas.com/tikz-snippets/fig-maxwell-boltzmann-speed-distribution/reduced-units.webp)

*the distribution in reduced units u = v/v_p, with the tail above 2v_p shaded*

Preamble: `\usepackage{tikz}`, `\usepackage{pgfplots}`, `\pgfplotsset{compat=1.18}`

```latex
\begin{tikzpicture}
  \begin{axis}[
      width=8.5cm, height=5.5cm, axis lines=left, ymin=0, ymax=0.95,
      domain=0:3.5, samples=100, smooth, no markers, enlarge x limits=false,
      xlabel={$u = v/v_p$}, ylabel={$v_p\,f(v)$},
    ]
    % in units of vp every temperature gives the same curve
    \addplot[draw=none, fill=orange!40, domain=2:3.5] {4/sqrt(pi)*x^2*exp(-x^2)} \closedcycle;
    \addplot[very thick, blue!70!black] {4/sqrt(pi)*x^2*exp(-x^2)};
    \draw[dashed] (axis cs:1,0) -- (axis cs:1,{4/sqrt(pi)*exp(-1)});
    \node[font=\small, anchor=west] at (axis cs:1.08,0.84) {most probable speed, $u = 1$};
    \node[font=\small, anchor=south east, align=left] at (axis cs:3.45,0.22)
      {4.6\,\% of the particles\\are faster than $2v_p$};
  \end{axis}
\end{tikzpicture}
```

## Frequently asked questions

### How do I plot the Maxwell–Boltzmann distribution in LaTeX?

Use pgfplots: \addplot[domain=0:8000, samples=100, smooth] {4*pi*(m/(2*pi*k*T))^(3/2)*x^2*exp(-m*x^2/(2*k*T))}; with the constants written in or stored in macros. pgfplots evaluates the expression with its floating-point unit, so constants like 1.38e-23 are fine.

### Why does TikZ give “Dimension too large” for my formula?

TikZ’s own arithmetic (in \draw plot or coordinates) works with numbers up to about 16383. Plot with pgfplots, whose \addplot uses a floating-point unit, or rescale the formula so the numbers stay small, for example in units of the most probable speed.

### Why does $\mu$ print a number in this document?

Line 11 redefines \mu as the atomic mass unit for the formula. Any later $\mu$ in the same document expands to 1.66e-27. Give the constant another name, such as \massu.

## References

- [janosh/diagrams at commit 7a79b31: assets/maxwell-boltzmann-distribution/maxwell-boltzmann-distribution.tex (MIT licence)](https://github.com/janosh/diagrams/blob/7a79b3114e201fad9b6785e936eab859d1bc8c12/assets/maxwell-boltzmann-distribution/maxwell-boltzmann-distribution.tex)
- [pgfplots manual, §4.3.3 Computing Coordinates with Mathematical Expressions (domain, samples, the floating-point unit)](https://tikz.dev/pgfplots/reference-addplot#sec-4.3.3)
- [pgfplots manual, §4.5.2 Smooth Plots](https://tikz.dev/pgfplots/reference-2dplots#sec-4.5.2)
- [pgfplots manual, §4.5.11 Closing Plots (Filling the Area Under Plots)](https://tikz.dev/pgfplots/reference-2dplots#sec-4.5.11)
- [pgfplots manual, §4.7.7 Cycle Lists](https://tikz.dev/pgfplots/reference-markers#sec-4.7.7)
- [pgfplots manual, §4.9.4 Legends and §4.9.5 Legend Appearance](https://tikz.dev/pgfplots/reference-axisdescription#sec-4.9.4)
- [pgfplots manual (v1.18.3), §2.2 Upgrade remarks (the compat key)](https://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplots.pdf)
- [PGF/TikZ manual, §96 Customizing the Mathematical Engine (\pgfmathdeclarefunction)](https://tikz.dev/math-algorithms)
- [siunitx package on CTAN (v3): \unit, \qty and the version 2 names \si and \SI](https://ctan.org/pkg/siunitx)

## TikZ guides for these techniques

- [TikZ plots with pgfplots: functions, data, scatter, bars and 3D](https://www.labcanvas.com/tikz/plots): Plot in LaTeX with pgfplots: functions, data tables, scatter plots coloured by value, error bars, bar charts, log axes, 3D surfaces and groupplots.
- [TikZ physics diagrams: forces, springs, optics, waves and fields](https://www.labcanvas.com/tikz/physics-diagrams): Physics diagrams in TikZ with code: free-body diagram, inclined plane, spring and pendulum, a lens ray diagram, waves, energy levels and a dipole field.
- [TikZ colors: names, mixing, fill, shading and patterns](https://www.labcanvas.com/tikz/colors): TikZ colours with xcolor: every named colour (base and dvipsnames charts), red!30 mixing, custom colours, fill and filldraw, opacity, shading, patterns.
