You are reading an old version of the documentation (v2.0.2). For the latest version see https://matplotlib.org/stable/
Image
matplotlib
Image
Travis-CI: Image

Table Of Contents

This Page

Writing mathematical expressions

You can use a subset TeX markup in any matplotlib text string by placing it inside a pair of dollar signs ($).

Note that you do not need to have TeX installed, since matplotlib ships its own TeX expression parser, layout engine and fonts. The layout engine is a fairly direct adaptation of the layout algorithms in Donald Knuth’s TeX, so the quality is quite good (matplotlib also provides a usetex option for those who do want to call out to TeX to generate their text (see Text rendering With LaTeX).

Any text element can use math text. You should use raw strings (precede the quotes with an 'r'), and surround the math text with dollar signs ($), as in TeX. Regular text and mathtext can be interleaved within the same string. Mathtext can use DejaVu Sans (default), DejaVu Serif, the Computer Modern fonts (from (La)TeX), STIX fonts (with are designed to blend well with Times), or a Unicode font that you provide. The mathtext font can be selected with the customization variable mathtext.fontset (see Customizing matplotlib)

Note

On “narrow” builds of Python, if you use the STIX fonts you should also set ps.fonttype and pdf.fonttype to 3 (the default), not 42. Otherwise some characters will not be visible.

Here is a simple example:

# plain text
plt.title('alpha > beta')

produces “alpha > beta”.

Whereas this:

# math text
plt.title(r'$\alpha > \beta$')

produces “Image”.

Note

Mathtext should be placed between a pair of dollar signs ($). To make it easy to display monetary values, e.g., “$100.00”, if a single dollar sign is present in the entire string, it will be displayed verbatim as a dollar sign. This is a small change from regular TeX, where the dollar sign in non-math text would have to be escaped (‘\$’).

Note

While the syntax inside the pair of dollar signs ($) aims to be TeX-like, the text outside does not. In particular, characters such as:

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

have special meaning outside of math mode in TeX. Therefore, these characters will behave differently depending on the rcParam text.usetex flag. See the usetex tutorial for more information.

Subscripts and superscripts

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

r'$\alpha_i > \beta_i$'
Image

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

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

Fractions, binomials and stacked numbers

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

r'$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$'

produces

Image

Fractions can be arbitrarily nested:

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

produces

Image

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

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

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

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

Radicals

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

r'$\sqrt{2}$'
Image

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

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

Fonts

The default font is italics for mathematical symbols.

Note

This default can be changed using the mathtext.default rcParam. This is useful, for example, to use the same font as regular non-math text for math text, by setting it to regular.

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

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

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

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

Here “s” and “t” are variable in italics font (default), “sin” is in Roman font, and the amplitude “A” is in calligraphy font. Note in the example above the caligraphy A is squished into the sin. You can use a spacing command to add a little whitespace between them:

s(t) = \mathcal{A}\/\sin(2 \omega t)
Image

The choices available with all fonts are:

Command Result
\mathrm{Roman} Image
\mathit{Italic} Image
\mathtt{Typewriter} Image
\mathcal{CALLIGRAPHY} Image

When using the STIX fonts, you also have the choice of:

Command Result
\mathbb{blackboard} Image
\mathrm{\mathbb{blackboard}} Image
\mathfrak{Fraktur} Image
\mathsf{sansserif} Image
\mathrm{\mathsf{sansserif}} Image
\mathcircled{circled} Image

There are also three global “font sets” to choose from, which are selected using the mathtext.fontset parameter in matplotlibrc.

cm: Computer Modern (TeX)

../_images/cm_fontset.png

stix: STIX (designed to blend well with Times)

../_images/stix_fontset.png

stixsans: STIX sans-serif

../_images/stixsans_fontset.png

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

Custom fonts

mathtext also provides a way to use custom fonts for math. This method is fairly tricky to use, and should be considered an experimental feature for patient users only. By setting the rcParam mathtext.fontset to custom, you can then set the following parameters, which control which font file to use for 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 italic
mathtext.cal \mathcal{} calligraphic
mathtext.sf \mathsf{} sans-serif

Each parameter should be set to a fontconfig font descriptor (as defined in the yet-to-be-written font chapter).

The fonts used should have a Unicode mapping in order to find any non-Latin characters, such as Greek. If you want to use a math symbol that is not contained in your custom fonts, you can set the rcParam mathtext.fallback_to_cm to True which will cause the mathtext system to use characters from the default Computer Modern fonts whenever a particular character can not be found in the custom font.

Note that the math glyphs specified in Unicode have evolved over time, and many 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 are long and short forms for some of them.

Command Result
\acute a or \'a Image
\bar a Image
\breve a Image
\ddot a or \"a Image
\dot a or \.a Image
\grave a or \`a Image
\hat a or \^a Image
\tilde a or \~a Image
\vec a Image
\overline{abc} Image

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

Command Result
\widehat{xyz} Image
\widetilde{xyz} Image

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

r"$\hat i\ \ \hat \imath$"
Image

Symbols

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

Lower-case Greek

Image \alpha Image \beta Image \chi Image \delta Image \digamma
Image \epsilon Image \eta Image \gamma Image \iota Image \kappa
Image \lambda Image \mu Image \nu Image \omega Image \phi
Image \pi Image \psi Image \rho Image \sigma Image \tau
Image \theta Image \upsilon Image \varepsilon Image \varkappa Image \varphi
Image \varpi Image \varrho Image \varsigma Image \vartheta Image \xi
Image \zeta        

Upper-case Greek

Image \Delta Image \Gamma Image \Lambda Image \Omega Image \Phi Image \Pi
Image \Psi Image \Sigma Image \Theta Image \Upsilon Image \Xi Image \mho
Image \nabla          

Hebrew

Image \aleph Image \beth Image \daleth Image \gimel

Delimiters

Image / Image [ Image \Downarrow Image \Uparrow Image \Vert Image \backslash
Image \downarrow Image \langle Image \lceil Image \lfloor Image \llcorner Image \lrcorner
Image \rangle Image \rceil Image \rfloor Image \ulcorner Image \uparrow Image \urcorner
Image \vert Image \{ Image \| Image \} Image ] Image |

Big symbols

Image \bigcap Image \bigcup Image \bigodot Image \bigoplus Image \bigotimes
Image \biguplus Image \bigvee Image \bigwedge Image \coprod Image \int
Image \oint Image \prod Image \sum    

Standard function names

Image \Pr Image \arccos Image \arcsin Image \arctan
Image \arg Image \cos Image \cosh Image \cot
Image \coth Image \csc Image \deg Image \det
Image \dim Image \exp Image \gcd Image \hom
Image \inf Image \ker Image \lg Image \lim
Image \liminf Image \limsup Image \ln Image \log
Image \max Image \min Image \sec Image \sin
Image \sinh Image \sup Image \tan Image \tanh

Binary operation and relation symbols

Image \Bumpeq Image \Cap Image \Cup
Image \Doteq Image \Join Image \Subset
Image \Supset Image \Vdash Image \Vvdash
Image \approx Image \approxeq Image \ast
Image \asymp Image \backepsilon Image \backsim
Image \backsimeq Image \barwedge Image \because
Image \between Image \bigcirc Image \bigtriangledown
Image \bigtriangleup Image \blacktriangleleft Image \blacktriangleright
Image \bot Image \bowtie Image \boxdot
Image \boxminus Image \boxplus Image \boxtimes
Image \bullet Image \bumpeq Image \cap
Image \cdot Image \circ Image \circeq
Image \coloneq Image \cong Image \cup
Image \curlyeqprec Image \curlyeqsucc Image \curlyvee
Image \curlywedge Image \dag Image \dashv
Image \ddag Image \diamond Image \div
Image \divideontimes Image \doteq Image \doteqdot
Image \dotplus Image \doublebarwedge Image \eqcirc
Image \eqcolon Image \eqsim Image \eqslantgtr
Image \eqslantless Image \equiv Image \fallingdotseq
Image \frown Image \geq Image \geqq
Image \geqslant Image \gg Image \ggg
Image \gnapprox Image \gneqq Image \gnsim
Image \gtrapprox Image \gtrdot Image \gtreqless
Image \gtreqqless Image \gtrless Image \gtrsim
Image \in Image \intercal Image \leftthreetimes
Image \leq Image \leqq Image \leqslant
Image \lessapprox Image \lessdot Image \lesseqgtr
Image \lesseqqgtr Image \lessgtr Image \lesssim
Image \ll Image \lll Image \lnapprox
Image \lneqq Image \lnsim Image \ltimes
Image \mid Image \models Image \mp
Image \nVDash Image \nVdash Image \napprox
Image \ncong Image \ne Image \neq
Image \neq Image \nequiv Image \ngeq
Image \ngtr Image \ni Image \nleq
Image \nless Image \nmid Image \notin
Image \nparallel Image \nprec Image \nsim
Image \nsubset Image \nsubseteq Image \nsucc
Image \nsupset Image \nsupseteq Image \ntriangleleft
Image \ntrianglelefteq Image \ntriangleright Image \ntrianglerighteq
Image \nvDash Image \nvdash Image \odot
Image \ominus Image \oplus Image \oslash
Image \otimes Image \parallel Image \perp
Image \pitchfork Image \pm Image \prec
Image \precapprox Image \preccurlyeq Image \preceq
Image \precnapprox Image \precnsim Image \precsim
Image \propto Image \rightthreetimes Image \risingdotseq
Image \rtimes Image \sim Image \simeq
Image \slash Image \smile Image \sqcap
Image \sqcup Image \sqsubset Image \sqsubset
Image \sqsubseteq Image \sqsupset Image \sqsupset
Image \sqsupseteq Image \star Image \subset
Image \subseteq Image \subseteqq Image \subsetneq
Image \subsetneqq Image \succ Image \succapprox
Image \succcurlyeq Image \succeq Image \succnapprox
Image \succnsim Image \succsim Image \supset
Image \supseteq Image \supseteqq Image \supsetneq
Image \supsetneqq Image \therefore Image \times
Image \top Image \triangleleft Image \trianglelefteq
Image \triangleq Image \triangleright Image \trianglerighteq
Image \uplus Image \vDash Image \varpropto
Image \vartriangleleft Image \vartriangleright Image \vdash
Image \vee Image \veebar Image \wedge
Image \wr    

Arrow symbols

Image \Downarrow Image \Leftarrow
Image \Leftrightarrow Image \Lleftarrow
Image \Longleftarrow Image \Longleftrightarrow
Image \Longrightarrow Image \Lsh
Image \Nearrow Image \Nwarrow
Image \Rightarrow Image \Rrightarrow
Image \Rsh Image \Searrow
Image \Swarrow Image \Uparrow
Image \Updownarrow Image \circlearrowleft
Image \circlearrowright Image \curvearrowleft
Image \curvearrowright Image \dashleftarrow
Image \dashrightarrow Image \downarrow
Image \downdownarrows Image \downharpoonleft
Image \downharpoonright Image \hookleftarrow
Image \hookrightarrow Image \leadsto
Image \leftarrow Image \leftarrowtail
Image \leftharpoondown Image \leftharpoonup
Image \leftleftarrows Image \leftrightarrow
Image \leftrightarrows Image \leftrightharpoons
Image \leftrightsquigarrow Image \leftsquigarrow
Image \longleftarrow Image \longleftrightarrow
Image \longmapsto Image \longrightarrow
Image \looparrowleft Image \looparrowright
Image \mapsto Image \multimap
Image \nLeftarrow Image \nLeftrightarrow
Image \nRightarrow Image \nearrow
Image \nleftarrow Image \nleftrightarrow
Image \nrightarrow Image \nwarrow
Image \rightarrow Image \rightarrowtail
Image \rightharpoondown Image \rightharpoonup
Image \rightleftarrows Image \rightleftarrows
Image \rightleftharpoons Image \rightleftharpoons
Image \rightrightarrows Image \rightrightarrows
Image \rightsquigarrow Image \searrow
Image \swarrow Image \to
Image \twoheadleftarrow Image \twoheadrightarrow
Image \uparrow Image \updownarrow
Image \updownarrow Image \upharpoonleft
Image \upharpoonright Image \upuparrows
   

Miscellaneous symbols

Image \$ Image \AA Image \Finv
Image \Game Image \Im Image \P
Image \Re Image \S Image \angle
Image \backprime Image \bigstar Image \blacksquare
Image \blacktriangle Image \blacktriangledown Image \cdots
Image \checkmark Image \circledR Image \circledS
Image \clubsuit Image \complement Image \copyright
Image \ddots Image \diamondsuit Image \ell
Image \emptyset Image \eth Image \exists
Image \flat Image \forall Image \hbar
Image \heartsuit Image \hslash Image \iiint
Image \iint Image \iint Image \imath
Image \infty Image \jmath Image \ldots
Image \measuredangle Image \natural Image \neg
Image \nexists Image \oiiint Image \partial
Image \prime Image \sharp Image \spadesuit
Image \sphericalangle Image \ss Image \triangledown
Image \varnothing Image \vartriangle Image \vdots
Image \wp Image \yen  

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

ur'$\u23ce$'

Example

Here is an example illustrating many of these features in context.

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

(Source code, png, pdf)

../_images/pyplot_mathtext.png