Note

Go to the endto download the full example code.

Writing mathematical expressions#

Matplotlib implements a lightweight TeX expression parser and layout engine andMathtext is the subset of Tex markup that this engine supports. Note thatMatplotlib can also render all text directly using TeX ifrcParams["text.usetex"] (default:False) isTrue; seeText rendering with LaTeX for more details. Mathtext support is availableifrcParams["text.usetex"] (default:False) isFalse.

Any string can be processed as Mathtext by placing the string inside a pair ofdollar signs'$'. Mathtext often contains many backslashes'\'; so thatthe backslashes do not need to be escaped, Mathtext is often written using rawstrings. For example:

importmatplotlib.pyplotaspltfig=plt.figure(figsize=(3,3),linewidth=1,edgecolor='black')fig.text(.2,.7,"plain text: alpha > beta")fig.text(.2,.5,"Mathtext: $\\alpha >\\beta$")fig.text(.2,.3,r"raw string Mathtext: $\alpha > \beta$")
mathtext

TeX doesnot need to be installed to use Mathtext because Matplotlib shipswith the Mathtext parser and engine. The Mathtext layout engine is a fairlydirect adaptation of the layout algorithms in Donald Knuth's TeX. To rendermathematical text using a different TeX engine, seeText rendering with LaTeX.

Note

To generate html output in documentation that will exactly match the outputgenerated bymathtext, use thematplotlib.sphinxext.mathmpl Sphinxextension.

Special characters#

Mathtext must be placed between a pair of (US) dollar signs'$'. A literaldollar symbol'$' in a string containing Mathtext must be escaped using abackslash:'\$'. A string may contain multiple pairs of dollar signs,resulting in multiple Mathtext expressions. Strings with an odd number ofdollar signs are rendered solely as plain text.

fig=plt.figure(figsize=(3,3),linewidth=1,edgecolor='black')fig.suptitle("Number of unescaped $")fig.text(.1,.7,r"odd: $ \alpha $ = $1")fig.text(.1,.5,r"even: $ \beta $= $ 2 $")fig.text(.1,.3,r'odd: $ \gamma $= \$3 $')fig.text(.1,.1,r'even: $ \delta $ = $ \$4 $')
Number of unescaped $

While Mathtext aims for compatibility with regular TeX, it diverges on whenspecial characters need to be escaped. In TeX the dollar sign must be escaped'\$' in non-math text, while in Matplotlib the dollar sign must beescaped when writing Mathtext.

These other special characters are also escaped in non-math TeX, while inMatplotlib their behavior is dependent on howrcParams["text.usetex"] (default:False) is set:

# $ % & ~ _ ^ \ { } \( \) \[ \]

See theusetex tutorial for more information.

Subscripts and superscripts#

To make subscripts and superscripts, use the'_' and'^' symbols:

r'$\alpha_i > \beta_i$'
\[\alpha_i > \beta_i\]

To display multi-letter subscripts or superscripts correctly,you should put them in curly braces{...}:

r'$\alpha^{ic} > \beta_{ic}$'
\[\alpha^{ic} > \beta_{ic}\]

Some symbols automatically put their sub/superscripts under and over theoperator. For example, to write the sum of from to, you could do:

r'$\sum_{i=0}^\infty x_i$'
\[\sum_{i=0}^\infty x_i\]

Fractions, binomials, and stacked numbers#

Fractions, binomials, and stacked numbers can be created with the\frac{}{},\binom{}{} and\genfrac{}{}{}{}{}{} commands,respectively:

r'$\frac{3}{4} \binom{3}{4} \genfrac{}{}{0}{}{3}{4}$'

produces

\[\frac{3}{4} \binom{3}{4} \genfrac{}{}{0pt}{}{3}{4}\]

Fractions can be arbitrarily nested:

r'$\frac{5 - \frac{1}{x}}{4}$'

produces

\[\frac{5 - \frac{1}{x}}{4}\]

Note that special care needs to be taken to place parentheses and bracketsaround fractions. Doing things the obvious way produces brackets that are toosmall:

r'$(\frac{5 - \frac{1}{x}}{4})$'
\[(\frac{5 - \frac{1}{x}}{4})\]

The solution is to precede the bracket with\left and\right to informthe parser that those brackets encompass the entire object.:

r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'
\[\left(\frac{5 - \frac{1}{x}}{4}\right)\]

Radicals#

Radicals can be produced with the\sqrt[]{} command. For example:

r'$\sqrt{2}$'
\[\sqrt{2}\]

Any base can (optionally) be provided inside square brackets. Note that thebase must be a simple expression, and cannot contain layout commands such asfractions or sub/superscripts:

r'$\sqrt[3]{x}$'
\[\sqrt[3]{x}\]

Fonts#

The default font isitalics for mathematical symbols.

This default can be changed usingrcParams["mathtext.default"] (default:'it'). For setting rcParams,seeCustomizing Matplotlib with style sheets and rcParams. For example, setting the default toregular allowsyou to use the same font for math text and regular non-math text.

To change fonts, e.g., to write "sin" in a Roman font, enclose the text in afont command:

r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$'
\[s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)\]

More conveniently, many commonly used function names that are typeset ina Roman font have shortcuts. So the expression above could be written asfollows:

r'$s(t) = \mathcal{A}\sin(2 \omega t)$'
\[s(t) = \mathcal{A}\sin(2 \omega t)\]

Here "s" and "t" are variable in italics font (default), "sin" is in Romanfont, and the amplitude "A" is in calligraphy font. Note in the example abovethe calligraphyA is squished into thesin. You can use a spacingcommand to add a little whitespace between them:

r's(t) = \mathcal{A}\/\sin(2 \omega t)'
\[s(t) = \mathcal{A}\,\sin(2 \omega t)\]

Mathtext can use DejaVu Sans (default), DejaVu Serif, Computer Modern fontsfrom (La)TeX,STIX fonts which are designedto blend well with Times, or a Unicode font that you provide. The Mathtextfont can be selected viarcParams["mathtext.fontset"] (default:'dejavusans').

The choices available with all fonts are:

Command

Result

\mathrm{Roman}

\mathit{Italic}

\mathtt{Typewriter}

\mathcal{CALLIGRAPHY}

When using theSTIX fonts, you also have thechoice of:

Command

Result

\mathbb{blackboard}

\mathrm{\mathbb{blackboard}}

\mathfrak{Fraktur}

\mathsf{sansserif}

\mathrm{\mathsf{sansserif}}

\mathbfit{bolditalic}

There are also five global "font sets" to choose from, which areselected using themathtext.fontset parameter inmatplotlibrc.

dejavusans: DejaVu Sans
dejavuserif: DejaVu Serif
cm: Computer Modern (TeX)
stix: STIX (designed to blend well with Times)
stixsans: STIX sans-serif

Additionally, you can use\mathdefault{...} or its alias\mathregular{...} to use the font used for regular text outside ofMathtext. There are a number of limitations to this approach, most notablythat far fewer symbols will be available, but it can be useful to make mathexpressions blend well with other text in the plot.

For compatibility with popular packages,\text{...} is available and uses the\mathrm{...} font, but otherwise retains spaces and renders - as a dash(not minus).

Custom fonts#

Mathtext also provides a way to use custom fonts for math. This method isfairly tricky to use, and should be considered an experimental feature forpatient users only. By settingrcParams["mathtext.fontset"] (default:'dejavusans') tocustom,you can then set the following parameters, which control which font file to usefor a particular set of math characters.

Parameter

Corresponds to

mathtext.it

\mathit{} or default italic

mathtext.rm

\mathrm{} Roman (upright)

mathtext.tt

\mathtt{} Typewriter (monospace)

mathtext.bf

\mathbf{} bold

mathtext.bfit

\mathbfit{} bold italic

mathtext.cal

\mathcal{} calligraphic

mathtext.sf

\mathsf{} sans-serif

Each parameter should be set to a fontconfig font descriptor, as defined inFonts in Matplotlib. The fonts used should have a Unicode mapping in order to findany non-Latin characters, such as Greek. If you want to use a math symbolthat is not contained in your custom fonts, you can setrcParams["mathtext.fallback"] (default:'cm') to either'cm','stix' or'stixsans'which will cause the Mathtext system to usecharacters from an alternative font whenever a particularcharacter cannot be found in the custom font.

Note that the math glyphs specified in Unicode have evolved over time, andmany fonts may not have glyphs in the correct place for Mathtext.

Accents#

An accent command may precede any symbol to add an accent above it. There arelong and short forms for some of them.

Command

Result

\acutea or\'a

\bara

\brevea

\dota or\.a

\ddota or\''a

\dddota

\ddddota

\gravea or\`a

\hata or\^a

\tildea or\~a

\veca

\overline{abc}

In addition, there are two special accents that automatically adjust to thewidth of the symbols below:

Command

Result

\widehat{xyz}

\widetilde{xyz}

Care should be taken when putting accents on lower-case i's and j's. Notethat in the following\imath is used to avoid the extra dot over the i:

r"$\hat i\ \ \hat \imath$"
\[\hat i\ \ \hat \imath\]

Symbols#

You can also use a large number of the TeX symbols, as in\infty,\leftarrow,\sum,\int.

Lower-case Greek

α\alpha

β\beta

γ\gamma

δ\delta

ε\epsilon

ε\varepsilon

ζ\zeta

η\eta

θ\theta

ϑ\vartheta

ι\iota

κ\kappa

ϰ\varkappa

λ\lambda

μ\mu

ν\nu

ξ\xi

π\pi

ϖ\varpi

ρ\rho

ϱ\varrho

σ\sigma

ς\varsigma

τ\tau

υ\upsilon

χ\chi

ψ\psi

ω\omega

ϕ\phi

φ\varphi

ϝ\digamma

Upper-case Greek

Γ\Gamma

Δ\Delta

Θ\Theta

Λ\Lambda

Ξ\Xi

Π\Pi

Σ\Sigma

Υ\Upsilon

Φ\Phi

Ψ\Psi

Ω\Omega

Hebrew

\daleth

\gimel

\beth

\aleph

Latin named characters

Å\AA

Æ\AE

Ð\DH

Ø\O

Þ\Thorn

ß\ss

å\aa

æ\ae

ð\eth

ð\dh

ø\o

þ\thorn

Œ\OE

œ\oe

Delimiters

(\leftparen

((

)\rightparen

))

..

//

<<

>>

[\lbrack

[[

\\backslash

|\vert

||

]]

]\rbrack

{\lbrace

{\leftbrace

{\{

}\}

}\rightbrace

}\rbrace

\|

\Vert

\uparrow

\downarrow

\updownarrow

\Uparrow

\Downarrow

\Updownarrow

\lceil

\rceil

\lfloor

\rfloor

\langle

\rangle

\lgroup

\rgroup

Big symbols

\prod

\coprod

\sum

\int

\iint

\iiint

\oint

\oiint

\oiiint

\bigwedge

\bigvee

\bigcap

\bigcup

\bigodot

\bigoplus

\bigotimes

\biguplus

\bigsqcup

\iiiint

Standard function names

Pr\Pr

arccos\arccos

arcsin\arcsin

arctan\arctan

arg\arg

cos\cos

cosh\cosh

cot\cot

coth\coth

csc\csc

deg\deg

det\det

dim\dim

exp\exp

gcd\gcd

hom\hom

inf\inf

ker\ker

lg\lg

lim\lim

liminf\liminf

limsup\limsup

ln\ln

log\log

max\max

min\min

sec\sec

sin\sin

sinh\sinh

sup\sup

tan\tan

tanh\tanh

Binary operation symbols

**

++

--

±\pm

×\times

÷\div

\dagger

\ddagger

\mp

\dotplus

\slash

\setminus

\ast

\circ

\bullet

\wedge

\vee

\cap

\cup

\dotminus

\minuscolon

\dotsminusdots

\wr

\cupdot

\uplus

\sqcap

\sqcup

\oplus

\ominus

\otimes

\oslash

\odot

\circledcirc

\circledast

\circleddash

\boxplus

\boxminus

\boxtimes

\boxdot

\unlhd

\unrhd

\intercal

\veebar

\barwedge

\barvee

\diamond

\cdot

\star

\divideontimes

\leftthreetimes

\rightthreetimes

\curlyvee

\curlywedge

\Cap

\Cup

\doublebarwedge

\obar

\bigtriangleup

\triangleright

\rhd

\bigtriangledown

\triangleleft

\lhd

\bigcirc

\boxbar

⨿\amalg

\merge

Relation symbols

::

<<

=\equal

==

>>

϶\backepsilon

\dots

\in

\notin

\smallin

\ni

\notsmallowns

\smallowns

\propto

\varpropto

\rightangle

\mid

\nmid

\parallel

\nparallel

\therefore

\because

\ratio

\sim

\backsim

\nsim

\eqsim

\simeq

\nsimeq

\cong

\simneqq

\ncong

\approx

\napprox

\approxeq

\approxident

\backcong

\asymp

\Bumpeq

\bumpeq

\doteq

\doteqdot

\Doteq

\fallingdotseq

\risingdotseq

\coloneq

\eqcolon

\eqcirc

\circeq

\arceq

\wedgeq

\veeeq

\stareq

\triangleeq

\triangleq

\eqdef

\measeq

\questeq

\ne

\neq

\equiv

\nequiv

\Equiv

\leq

\geq

\leqq

\geqq

\lneqq

\gneqq

\ll

\gg

\between

\nless

\ngtr

\nleq

\ngeq

\lesssim

\gtrsim

\nlesssim

\ngtrsim

\lessgtr

\gtrless

\nlessgtr

\ngtrless

\prec

\succ

\preceq

\preccurlyeq

\succeq

\succcurlyeq

\precsim

\succsim

\nprec

\nsucc

\subset

\supset

\nsubset

\nsupset

\subseteq

\supseteq

\nsubseteq

\nsupseteq

\subsetneq

\supsetneq

\sqsubset

\sqsupset

\sqsubseteq

\sqsupseteq

\oequal

\vdash

\dashv

\top

\bot

\rightassert

\models

\vDash

\Vdash

\Vvdash

\rightModels

\nvdash

\nvDash

\nVdash

\nVDash

\scurel

\trianglelefteq

\trianglerighteq

\measuredrightangle

\varlrtriangle

\bowtie

\ltimes

\rtimes

\backsimeq

\Subset

\Supset

\pitchfork

\equalparallel

\lessdot

\gtrdot

\lll

\ggg

\lesseqgtr

\gtreqless

\eqless

\eqgtr

\curlyeqprec

\curlyeqsucc

\npreccurlyeq

\nsucccurlyeq

\nsqsubseteq

\nsqsupseteq

\sqsubsetneq

\sqsupsetneq

\lnsim

\gnsim

\precnsim

\succnsim

\ntriangleleft

\ntriangleright

\ntrianglelefteq

\ntrianglerighteq

\disin

\isins

\varisins

\isindot

\isinobar

\varisinobar

\isinvb

\isinE

\nisd

\nis

\varnis

\niobar

\varniobar

\bagmember

\frown

\smile

\triangle

\blacktriangleright

\triangleright

\vartriangleright

\blacktriangleleft

\triangleleft

\vartriangleleft

\perp

\Join

\leqslant

\geqslant

\lessapprox

\gtrapprox

\lnapprox

\gnapprox

\lesseqqgtr

\gtreqqless

\eqslantless

\eqslantgtr

\precapprox

\succapprox

\precnapprox

\succnapprox

\subseteqq

\supseteqq

\subsetneqq

\supsetneqq

Arrow symbols

\overleftarrow

\overleftrightarrow

\leftarrow

\uparrow

\rightarrow

\to

\downarrow

\leftrightarrow

\updownarrow

\nwarrow

\nearrow

\searrow

\swarrow

\nleftarrow

\nrightarrow

\leftsquigarrow

\rightsquigarrow

\twoheadleftarrow

\twoheaduparrow

\twoheadrightarrow

\twoheaddownarrow

\leftarrowtail

\rightarrowtail

\mapsfrom

\mapsup

\mapsto

\mapsdown

\updownarrowbar

\hookleftarrow

\hookrightarrow

\looparrowleft

\looparrowright

\leftrightsquigarrow

\nleftrightarrow

\downzigzagarrow

\Lsh

\Rsh

\Ldsh

\Rdsh

\curvearrowleft

\curvearrowright

\circlearrowleft

\circlearrowright

\cwopencirclearrow

\leftharpoonup

\leftharpoondown

\upharpoonright

\upharpoonleft

\rightharpoonup

\rightharpoondown

\downharpoonright

\downharpoonleft

\rightleftarrows

\updownarrows

\leftrightarrows

\leftleftarrows

\upuparrows

\rightrightarrows

\downdownarrows

\leftrightharpoons

\rightleftharpoons

\nLeftarrow

\nLeftrightarrow

\nRightarrow

\Leftarrow

\Uparrow

\Rightarrow

\Downarrow

\Leftrightarrow

\Updownarrow

\Nwarrow

\Nearrow

\Searrow

\Swarrow

\Lleftarrow

\Rrightarrow

\leadsto

\rightzigzagarrow

\barleftarrow

\rightarrowbar

\cupleftarrow

\multimap

\longleftarrow

\longrightarrow

\longleftrightarrow

\Longleftarrow

\Longrightarrow

\Longleftrightarrow

\longmapsto

\dashleftarrow

\dashrightarrow

Dot symbols

\ldots

\therefore

\because

\Colon

\vdots

\cdots

\adots

\ddots

Black-board characters

\BbbC

\BbbN

\BbbP

\BbbQ

\BbbR

\BbbZ

Script characters

\scrg

\scrH

\scrI

\scrL

\scrR

\scrB

\scre

\scrE

\scrF

\scrM

\scro

Fraktur characters

\frakZ

\frakC

Miscellaneous symbols

$\$

¢\cent

£\sterling

¥\yen

§\S

©\copyright

¬\neg

®\circledR

°\degree

\P

ħ\hbar

ı\imath

ı\i

Ł\L

ł\l

ƛ\lambdabar

ȷ\jmath

\dag

\ddag

\perthousand

\prime

\backprime

\hslash

\Im

\ell

\wp

\Re

\mho

\Finv

\Game

\forall

\complement

\partial

\exists

\nexists

\emptyset

\varnothing

\increment

\nabla

\QED

\infty

\angle

\measuredangle

\sphericalangle

\ac

\sinewave

\hermitmatrix

\circledS

\blacksquare

\triangle

\vartriangle

\blacktriangle

\blacktriangledown

\triangledown

\bigstar

\danger

\spadesuit

\heartsuit

\diamondsuit

\clubsuit

\clubsuitopen

\flat

\natural

\sharp

\checkmark

\maltese

If a particular symbol does not have a name (as is true of many of the moreobscure symbols in the STIX fonts), Unicode characters can also be used:

'$\u23ce$'

Gallery generated by Sphinx-Gallery