{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/text/mathtext\n\n\n# Writing mathematical expressions\n\nMatplotlib implements a lightweight TeX expression parser and layout engine and\n*Mathtext* is the subset of Tex markup that this engine supports. Note that\nMatplotlib can also render all text directly using TeX if :rc:`text.usetex` is\n*True*; see `usetex` for more details. Mathtext support is available\nif :rc:`text.usetex` is *False*.\n\nAny string can be processed as Mathtext by placing the string inside a pair of\ndollar signs ``'$'``. Mathtext often contains many backslashes ``'\\'``; so that\nthe backslashes do not need to be escaped, Mathtext is often written using raw\nstrings. For example:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(3, 3), linewidth=1, edgecolor='black')\nfig.text(.2, .7, \"plain text: alpha > beta\")\nfig.text(.2, .5, \"Mathtext: $\\\\alpha > \\\\beta$\")\nfig.text(.2, .3, r\"raw string Mathtext: $\\alpha > \\beta$\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. seealso::\n\n :doc:`Mathtext example `\n\nTeX does *not* need to be installed to use Mathtext because Matplotlib ships\nwith the Mathtext parser and engine. The Mathtext layout engine is a fairly\ndirect adaptation of the layout algorithms in Donald Knuth's TeX. To render\nmathematical text using a different TeX engine, see `usetex`.\n\n

Note

To generate html output in documentation that will exactly match the output\n generated by ``mathtext``, use the `matplotlib.sphinxext.mathmpl` Sphinx\n extension.

\n\n\n## Special characters\n\nMathtext must be placed between a pair of (US) dollar signs ``'$'``. A literal\ndollar symbol ``'$'`` in a string containing Mathtext must be escaped using a\nbackslash: ``'\\$'``. A string may contain multiple pairs of dollar signs,\nresulting in multiple Mathtext expressions. Strings with an odd number of\ndollar signs are rendered solely as plain text.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(3, 3), linewidth=1, edgecolor='black')\nfig.suptitle(\"Number of unescaped $\")\nfig.text(.1, .7, r\"odd: $ \\alpha $ = $1\")\nfig.text(.1, .5, r\"even: $ \\beta $= $ 2 $\")\nfig.text(.1, .3, r'odd: $ \\gamma $= \\$3 $')\nfig.text(.1, .1, r'even: $ \\delta $ = $ \\$4 $')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While Mathtext aims for compatibility with regular TeX, it diverges on when\nspecial characters need to be escaped. In TeX the dollar sign must be escaped\n``'\\$'`` in non-math text, while in Matplotlib the dollar sign must be\nescaped when writing Mathtext.\n\nThese other special characters are also escaped in non-math TeX, while in\nMatplotlib their behavior is dependent on how :rc:`text.usetex` is set::\n\n # $ % & ~ _ ^ \\ { } \\( \\) \\[ \\]\n\nSee the `usetex tutorial ` for more information.\n\n\n## Subscripts and superscripts\nTo make subscripts and superscripts, use the ``'_'`` and ``'^'`` symbols::\n\n r'$\\alpha_i > \\beta_i$'\n\n\\begin{align}\\alpha_i > \\beta_i\\end{align}\n\nTo display multi-letter subscripts or superscripts correctly,\nyou should put them in curly braces ``{...}``::\n\n r'$\\alpha^{ic} > \\beta_{ic}$'\n\n\\begin{align}\\alpha^{ic} > \\beta_{ic}\\end{align}\n\nSome symbols automatically put their sub/superscripts under and over the\noperator. For example, to write the sum of :mathmpl:`x_i` from :mathmpl:`0` to\n:mathmpl:`\\infty`, you could do::\n\n r'$\\sum_{i=0}^\\infty x_i$'\n\n\\begin{align}\\sum_{i=0}^\\infty x_i\\end{align}\n\n## Fractions, binomials, and stacked numbers\nFractions, binomials, and stacked numbers can be created with the\n``\\frac{}{}``, ``\\binom{}{}`` and ``\\genfrac{}{}{}{}{}{}`` commands,\nrespectively::\n\n r'$\\frac{3}{4} \\binom{3}{4} \\genfrac{}{}{0}{}{3}{4}$'\n\nproduces\n\n\\begin{align}\\frac{3}{4} \\binom{3}{4} \\genfrac{}{}{0pt}{}{3}{4}\\end{align}\n\nFractions can be arbitrarily nested::\n\n r'$\\frac{5 - \\frac{1}{x}}{4}$'\n\nproduces\n\n\\begin{align}\\frac{5 - \\frac{1}{x}}{4}\\end{align}\n\nNote that special care needs to be taken to place parentheses and brackets\naround fractions. Doing things the obvious way produces brackets that are too\nsmall::\n\n r'$(\\frac{5 - \\frac{1}{x}}{4})$'\n\n\\begin{align}(\\frac{5 - \\frac{1}{x}}{4})\\end{align}\n\nThe solution is to precede the bracket with ``\\left`` and ``\\right`` to inform\nthe parser that those brackets encompass the entire object.::\n\n r'$\\left(\\frac{5 - \\frac{1}{x}}{4}\\right)$'\n\n\\begin{align}\\left(\\frac{5 - \\frac{1}{x}}{4}\\right)\\end{align}\n\n## Radicals\nRadicals can be produced with the ``\\sqrt[]{}`` command. For example::\n\n r'$\\sqrt{2}$'\n\n\\begin{align}\\sqrt{2}\\end{align}\n\nAny base can (optionally) be provided inside square brackets. Note that the\nbase must be a simple expression, and cannot contain layout commands such as\nfractions or sub/superscripts::\n\n r'$\\sqrt[3]{x}$'\n\n\\begin{align}\\sqrt[3]{x}\\end{align}\n\n\n## Fonts\n\nThe default font is *italics* for mathematical symbols.\n\nThis default can be changed using :rc:`mathtext.default`. For setting rcParams,\nsee `customizing`. For example, setting the default to ``regular`` allows\nyou to use the same font for math text and regular non-math text.\n\nTo change fonts, e.g., to write \"sin\" in a Roman font, enclose the text in a\nfont command::\n\n r'$s(t) = \\mathcal{A}\\mathrm{sin}(2 \\omega t)$'\n\n\\begin{align}s(t) = \\mathcal{A}\\mathrm{sin}(2 \\omega t)\\end{align}\n\nMore conveniently, many commonly used function names that are typeset in\na Roman font have shortcuts. So the expression above could be written as\nfollows::\n\n r'$s(t) = \\mathcal{A}\\sin(2 \\omega t)$'\n\n\\begin{align}s(t) = \\mathcal{A}\\sin(2 \\omega t)\\end{align}\n\nHere \"s\" and \"t\" are variable in italics font (default), \"sin\" is in Roman\nfont, and the amplitude \"A\" is in calligraphy font. Note in the example above\nthe calligraphy ``A`` is squished into the ``sin``. You can use a spacing\ncommand to add a little whitespace between them::\n\n r's(t) = \\mathcal{A}\\/\\sin(2 \\omega t)'\n\n.. Here we cheat a bit: for HTML math rendering, Sphinx relies on MathJax which\n doesn't actually support the italic correction (\\/); instead, use a thin\n space (\\,) which is supported.\n\n\\begin{align}s(t) = \\mathcal{A}\\,\\sin(2 \\omega t)\\end{align}\n\nMathtext can use DejaVu Sans (default), DejaVu Serif, Computer Modern fonts\nfrom (La)TeX, [STIX](http://www.stixfonts.org/) fonts which are designed\nto blend well with Times, or a Unicode font that you provide. The Mathtext\nfont can be selected via :rc:`mathtext.fontset`.\n\nThe choices available with all fonts are:\n\n========================= ================================\nCommand Result\n========================= ================================\n``\\mathrm{Roman}`` :mathmpl:`\\mathrm{Roman}`\n``\\mathit{Italic}`` :mathmpl:`\\mathit{Italic}`\n``\\mathtt{Typewriter}`` :mathmpl:`\\mathtt{Typewriter}`\n``\\mathcal{CALLIGRAPHY}`` :mathmpl:`\\mathcal{CALLIGRAPHY}`\n========================= ================================\n\n.. rstcheck: ignore-directives=role\n.. role:: math-stix(mathmpl)\n :fontset: stix\n\nWhen using the [STIX](http://www.stixfonts.org/) fonts, you also have the\nchoice of:\n\n================================ =========================================\nCommand Result\n================================ =========================================\n``\\mathbb{blackboard}`` :math-stix:`\\mathbb{blackboard}`\n``\\mathrm{\\mathbb{blackboard}}`` :math-stix:`\\mathrm{\\mathbb{blackboard}}`\n``\\mathfrak{Fraktur}`` :math-stix:`\\mathfrak{Fraktur}`\n``\\mathsf{sansserif}`` :math-stix:`\\mathsf{sansserif}`\n``\\mathrm{\\mathsf{sansserif}}`` :math-stix:`\\mathrm{\\mathsf{sansserif}}`\n``\\mathbfit{bolditalic}`` :math-stix:`\\mathbfit{bolditalic}`\n================================ =========================================\n\nThere are also five global \"font sets\" to choose from, which are\nselected using the ``mathtext.fontset`` parameter in `matplotlibrc\n`.\n\n``dejavusans``: DejaVu Sans\n .. mathmpl::\n :fontset: dejavusans\n\n \\mathcal{R} \\prod_{i=\\alpha}^{\\infty} a_i \\sin\\left(2\\pi fx_i\\right)\n\n``dejavuserif``: DejaVu Serif\n .. mathmpl::\n :fontset: dejavuserif\n\n \\mathcal{R} \\prod_{i=\\alpha}^{\\infty} a_i \\sin\\left(2\\pi fx_i\\right)\n\n``cm``: Computer Modern (TeX)\n .. mathmpl::\n :fontset: cm\n\n \\mathcal{R} \\prod_{i=\\alpha}^{\\infty} a_i \\sin\\left(2\\pi fx_i\\right)\n\n``stix``: STIX (designed to blend well with Times)\n .. mathmpl::\n :fontset: stix\n\n \\mathcal{R} \\prod_{i=\\alpha}^{\\infty} a_i \\sin\\left(2\\pi fx_i\\right)\n\n``stixsans``: STIX sans-serif\n .. mathmpl::\n :fontset: stixsans\n\n \\mathcal{R} \\prod_{i=\\alpha}^{\\infty} a_i \\sin\\left(2\\pi fx_i\\right)\n\nAdditionally, you can use ``\\mathdefault{...}`` or its alias\n``\\mathregular{...}`` to use the font used for regular text outside of\nMathtext. There are a number of limitations to this approach, most notably\nthat far fewer symbols will be available, but it can be useful to make math\nexpressions blend well with other text in the plot.\n\nFor compatibility with popular packages, ``\\text{...}`` is available and uses the\n``\\mathrm{...}`` font, but otherwise retains spaces and renders - as a dash\n(not minus).\n\n### Custom fonts\nMathtext also provides a way to use custom fonts for math. This method is\nfairly tricky to use, and should be considered an experimental feature for\npatient users only. By setting :rc:`mathtext.fontset` to ``custom``,\nyou can then set the following parameters, which control which font file to use\nfor a particular set of math characters.\n\n============================== =================================\nParameter Corresponds to\n============================== =================================\n``mathtext.it`` ``\\mathit{}`` or default italic\n``mathtext.rm`` ``\\mathrm{}`` Roman (upright)\n``mathtext.tt`` ``\\mathtt{}`` Typewriter (monospace)\n``mathtext.bf`` ``\\mathbf{}`` bold\n``mathtext.bfit`` ``\\mathbfit{}`` bold italic\n``mathtext.cal`` ``\\mathcal{}`` calligraphic\n``mathtext.sf`` ``\\mathsf{}`` sans-serif\n============================== =================================\n\nEach parameter should be set to a fontconfig font descriptor, as defined in\n`fonts`. The fonts used should have a Unicode mapping in order to find\nany non-Latin characters, such as Greek. If you want to use a math symbol\nthat is not contained in your custom fonts, you can set\n:rc:`mathtext.fallback` to either ``'cm'``, ``'stix'`` or ``'stixsans'``\nwhich will cause the Mathtext system to use\ncharacters from an alternative font whenever a particular\ncharacter cannot be found in the custom font.\n\nNote that the math glyphs specified in Unicode have evolved over time, and\nmany fonts may not have glyphs in the correct place for Mathtext.\n\n## Accents\nAn accent command may precede any symbol to add an accent above it. There are\nlong and short forms for some of them.\n\n============================== =================================\nCommand Result\n============================== =================================\n``\\acute a`` or ``\\'a`` :mathmpl:`\\acute a`\n``\\bar a`` :mathmpl:`\\bar a`\n``\\breve a`` :mathmpl:`\\breve a`\n``\\dot a`` or ``\\.a`` :mathmpl:`\\dot a`\n``\\ddot a`` or ``\\''a`` :mathmpl:`\\ddot a`\n``\\dddot a`` :mathmpl:`\\dddot a`\n``\\ddddot a`` :mathmpl:`\\ddddot a`\n``\\grave a`` or ``\\`a`` :mathmpl:`\\grave a`\n``\\hat a`` or ``\\^a`` :mathmpl:`\\hat a`\n``\\tilde a`` or ``\\~a`` :mathmpl:`\\tilde a`\n``\\vec a`` :mathmpl:`\\vec a`\n``\\overline{abc}`` :mathmpl:`\\overline{abc}`\n============================== =================================\n\nIn addition, there are two special accents that automatically adjust to the\nwidth of the symbols below:\n\n============================== =================================\nCommand Result\n============================== =================================\n``\\widehat{xyz}`` :mathmpl:`\\widehat{xyz}`\n``\\widetilde{xyz}`` :mathmpl:`\\widetilde{xyz}`\n============================== =================================\n\nCare should be taken when putting accents on lower-case i's and j's. Note\nthat in the following ``\\imath`` is used to avoid the extra dot over the i::\n\n r\"$\\hat i\\ \\ \\hat \\imath$\"\n\n\\begin{align}\\hat i\\ \\ \\hat \\imath\\end{align}\n\n## Symbols\nYou can also use a large number of the TeX symbols, as in ``\\infty``,\n``\\leftarrow``, ``\\sum``, ``\\int``.\n\n.. math_symbol_table::\n\nIf a particular symbol does not have a name (as is true of many of the more\nobscure symbols in the STIX fonts), Unicode characters can also be used::\n\n r'$\\u23ce$'\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }