Rendering text with LaTeX

If we want to plot more scientific graphics and explain math as it should be using scientific notations and complex equations on the figures, we need support from the best.

Although matplotlib has support for math text rendering, the best support comes from the LaTeX community, proven in the task being used for many decades.

LaTeX is a high-quality typesetting system for the production of scientific and technical documentation, being a de facto standard for scientific typesetting or publication. It is a free software, available on majority of desktop platforms used today as prepackages binary installation; hence, it is easy to install.

The basic syntax of LaTeX is similar to markup languages; so to produce satisfactory content, one would write focusing more on the structure than on the look and style. For example:

documentclass{article}
	itle{This here is a title of my document}
author{Peter J. S. Smith}
date{September 2013}
egin{document}
   maketitle
   Hello world, from LaTeX!
end{document}

We see how this is different from the usual word processor, where the WYSIWYG editor environment and the style is already applied to your text. Sometimes this is good but, for scientific publications, style is a secondary concern; the primary focus is having the right, correct, and valid content. Here, by content, we also mean mathematical notations (usually a lot of it), including graphs.

Apart from this, there are many more features such as automatic generation of bibliographies and indexes, which are important for medium to large publications. These are the main focus points of the LaTeX system.

Since this is not a book about LaTeX, we will stop with the quick introduction here. A lot more documentation is available on the project's website at http://latex-project.org/.

Getting ready

Before we start demonstrating matplotlib's support for rendering text using LaTeX, we need to have the following packages installed on our system:

  • LaTeX system: The most common one is the TeX Live prepackaged distribution
  • DVI to PNG converter: This makes PNG graphics from DVI files as obtained from TeX, by producing anti-aliased screen-resolution images
  • Ghost script: This is required, unless already installed by TeX Live distribution

There are different prepackaged systems of the LaTeX environment for different operating systems. For Linux-based systems, TeX Live is a complete TeX system. For Mac OS, the recommended environment is the MacTeX distribution; for the Windows environment, the proTeX system is going to install all the TeX supports, including LaTeX.

Whichever package you install, make sure it comes with font libraries and programs for typesetting, previewing, and printing of TeX documents in many different languages.

We will install our package for Linux using the texlive and dvipng packages for Ubuntu. We can install this using the following command:

$  sudo apt-get install texlivedvipng

The next step is to tell our matplotlib to use LaTeX by setting text.usetex to True. We can do that either in our custom .matplotlibrc inside our home directory (/home/<user>/.matplotlibrc on Unix-based systems, or C:Documents and Settings<user>.matplotlibrc) via rcParams['text'], or using the following code:

matplotlib.pyplot.rc('text', usetex=True)

The start of the code will tell matplotlib to go back to LaTeX for all text rendering. It is important to do this before we add any figure and axis.

Not all backends support LaTeX rendering. Only the Agg, PS, and PDF backends support text rendering via LaTeX.

How to do it...

What we want to do here is demonstrate the basic usage properties of LaTeX. We will perform the following steps:

  1. Generate some sample data.
  2. Set up matplotlib to use LaTeX for this plotting session.
  3. Set up the font and font properties to be used.
  4. Write out the equation syntax.
  5. Demonstrate the usage of Greek symbols' syntax.
  6. Draw math notations of fractions and fractals.
  7. Write some limits and exponential expressions.
  8. Write possible range expressions.
  9. Write expressions with text and formatted text in them.
  10. Write some math expressions on x and y labels as figure titles.

The following code will perform these steps:

import numpy as np
import matplotlib.pyplot as plt


# Example data 
t = np.arange(0.0, 1.0 + 0.01, 0.01) 
s = np.cos(4 * np.pi * t) * np.sin(np.pi*t/4) + 2 

plt.rc('text', usetex=True) 
plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'], 'size':16}) 

plt.plot(t, s, alpha=0.25) 

# first, the equation for 's' 
# note the usage of Python's raw strings
plt.annotate(r'$cos(4 	imes pi 	imes {t}) 	imes sin(pi 	imes frac {t} 4) + 2$', xy=(.9,2.2), xytext=(.5, 2.6), color='red', arrowprops={'arrowstyle':'->'}) 

# some math alphabet 
plt.text(.01, 2.7, r'$alpha, eta, gamma, Gamma, pi, Pi, phi, varphi, Phi$') 
# some equation 
plt.text(.01, 2.5, r'some equations $frac{n!}{k!(n-k)!} = {n choose k}$') 
# more equations 
plt.text(.01, 2.3, r'EQ1 $lim_{x 	o infty} exp(-x) = 0$') 
# some ranges... 
plt.text(.01, 2.1, r'Ranges: $( a ), [ b ], { c }, | d |, | e |, langle f 
angle, lfloor g 
floor, lceil h 
ceil$') 
# you can multiply apples and oranges 
plt.text(.01, 1.9, r'Text: $50 apples 	imes 100 oranges = lots of juice$') 
plt.text(.01, 1.7, r'More text formatting: $50 	extrm{ apples} 	imes 100 	extbf{ apples} = 	extit{lots of juice}$') 
plt.text(.01, 1.5, r'Some indexing: $eta = (eta_1,eta_2,dotsc,eta_n)$') 
# we can also write on labels 
plt.xlabel(r'	extbf{time} (s)') 
plt.ylabel(r'	extit{y values} (W)') 
# and write titles using LaTeX
plt.title(r"TeX is Number "
          r"$displaystylesum_{n=1}^inftyfrac{-e^{ipi}}{2^n}$!", 
fontsize=16, color='gray') 
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8) 

plt.savefig('tex_demo') 
plt.show()

The preceding code will render the following text-saturated figure that demonstrates LaTeX rendering:

How to do it...

How it works...

After we set up the rendering engine and font properties, we basically used standard matplotlib calls for text rendering, such as matplotlib.pyplot.annotate, matplotlib.pyplot.text, matplotlib.pyplot.xlabel, matplotlib.pyplot.ylabel, and matplotlib.pyplot.title.

The difference here is that all the strings are so-called raw strings, meaning that Python will not interpret them and no string substitution will occur; hence, the LaTeX engine is going to receive exactly the same strings as commands to act upon.

More examples of how to use TeX and how to integrate it in matplotlib can be found on the official matplotlib documentation at http://matplotlib.org/users/mathtext.html#writing-mathematical-expressions.

Note that this URL is not on LaTeX but on matplotlib's own integrated TeX parser. This parser supports almost the same syntax, and it can even be sufficient for your needs.

There's more...

If you run into a problem while setting up this environment or have different problems with fonts that either look bad or are not able to produce the LaTeX rendering, make sure that you have installed all required packages, your $PATH environment variable (if on Windows) is set up to include all the required binaries, and matplotlib is set to use LaTeX for text rendering.

If all of the given instructions are followed and the results cannot be replicated, refer to the official matplotlib website at http://matplotlib.org/users/usetex.html#possible-hangups and the LaTeX community on http://tex.stackexchange.com/ for further assistance.

It is known that this setup is not as streamlined as it should be, and some quirks may occur for various reasons.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.9