Monday, January 13, 2020

matplotlib for Mathematics and Greek symbols

matplotlib can display mathematical formulas, Greek letters, and mathematical symbols using a math rendering module known as mathtext. The mathtext module parses a subset of Donald Knuth’s TEX
mathematical typesetting language, and provides basic mathematical typesetting without any software other than matplotlib.

If, in addition, you have TEX (and/or LATEX) as a separate standalone program (such as MacTex [TexShop] or MiKTeX), then you can do even more. In what follows we will assume that you are using the native matplotlib mathtext, but will make a few comments applicable to those who have a separate installation of LATEX.

matplotlib’s mathtext can display Greek letters and mathematical symbols using the syntax of TEX. If you are familiar with TEX or LATEX, you have hardly anything to learn. Even if you are not familiar with them, the syntax is simple enough that you can employ it in most cases without too much effort.
You designate text as mathtext by placing dollar signs ($) in a text string at the beginning and end of any part of the string that you want to be rendered as math text. You should also use raw strings in most cases, which means you should precede the quotes of a string with the letter r. For example, the following commands produces a plot with the title “ pi > 3.”

plot([1, 2, 3, 2, 3, 4, 3, 4, 5])
title(r'$\pi > 3$')
pt.show()

Where the matplotlib function normally takes a string as input, you simply input the mathtext string. Note the r before the string in the title argument and the dollar signs ($) inside the quotes at the beginning and end of the text you wish to render as math text.

Subscripts and superscripts are designated using the underline “_” and caret “^” characters, respectively. Multiple characters to be included together in a subscript or superscript should be enclosed in a pair of curly braces {...}.

Now let's make a program to understand and implement what we have discussed. See the code below:

import numpy as np
import matplotlib.pyplot as plt


def f0(t, omega, gamma, tau):
    wt = omega * t
    f1 = np.sin(wt) + (np.cos(wt) - 1.0) / wt
    f2 = 1.0 + (gamma / omega) * f1
    return np.exp(-t * f2 / tau)


omega = 12.0
gamma = 8.0
tau = 1.0
t = np.linspace(0.01, 10.0, 500)
f = f0(t, omega, gamma, tau)

plt.rc('mathtext', fontset='stix')  # Use with mathtext
# plt.rc('text', usetex=True)        # Use with Latex
# plt.rc('font', family='serif')     # Use with Latex

fig, ax = plt.subplots(figsize=(7.5, 4.5))
ax.plot(t, f, color='C0')
ax.set_ylabel(r'$f_0(t)$', fontsize=14)
ax.set_xlabel(r'$t/\tau\quad\rm(ms)}$', fontsize=14)
ax.text(0.45, 0.95,
        r'$\Gamma(z)=\int_0^\infty x^{z-1}e^{-x}dx$',
        fontsize=16, ha='right', va='top',
        transform=ax.transAxes)
ax.text(0.45, 0.75,
        r'$e^x=\sum_{n=0}^\infty\frac{x^n}{n!}$',
        fontsize=16, ha='right', va='top',
        transform=ax.transAxes)
ax.text(0.45, 0.55,
        r'$\zeta(z)=\prod_{k=0}^\infty \frac{1}{1-p_k^{-z}}$',
        fontsize=16, ha='left', va='top',
        transform=ax.transAxes)
ax.text(0.95, 0.80,
        r'$\omega={0:0.1f},\;\gamma={1:0.1f},\;\tau={2:0.1f}$'
        .format(omega, gamma, tau),
        fontsize=14, ha='right', va='top',
        transform=ax.transAxes)
ax.text(0.85, 0.35,
        r'$e=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n$',
        fontsize=14, ha='right', va='top',
        transform=ax.transAxes)

fig.tight_layout()
fig.savefig('./figures/mplLatexDemo.pdf')
plt.show()


The output is shown below:


Line 18 sets the font to be used by mathtext, in this case stix. If you omit such a statement, mathtext uses its default font dejavusans. Other options include dejavuserif, cm (Computer Modern), stix, and
stixsans. 

Let’s see what LATEX can do. First, we see that the y-axis label in Figure shown above is f0(t), which has a subscript that was formatted using mathtext in line 24. The x-axis label is also typeset using mathtext, but the effects are more subtle in this case. The variable t is italicized, as is proper for a mathematical variable, but the units, (ms), are not, which is also standard practice. The math mode italics are turned off with the \rm (Roman) switch, which acts on text until the next closing curly brace (}).

Lines 26–29 provide the code to produce the expression for the Gamma function 􀀀 (z), lines 30–33 produce the expression for the Taylor series for the exponential function, and lines 34–37 produce the
product that gives the zeta function. Lines 38–42 provide the code that produces the expressions for !,
, and . Lines 43–46 provide the code that produces the limit expression for the natural logarithm base e. The mathtext (TEX) code that produces the four typeset equations is contained in strings in lines 27, 31, 35, 39, and 44. The strings begin and end with $ symbols, which activates and deactivates mathtext’s math mode.

Special commands and symbols begin with a backslash in mathtext, which follows the convention of TEX. However, Python strings also use backslashes for certain formatting commands, such as \t for
tab or \n for a new line. The r preceding the strings in lines 27, 31, 35, 39, and 44 makes those strings raw strings, which turns off Python’s special backslash formatting commands so that backslash commands are interpreted as mathtext.







Share:

0 comments:

Post a Comment