Search code examples
pythonmatplotliblatexmacports

Matplotlib raw latex "\epsilon" only yields "\varepsilon"


I'm using Matplotlib to analyze results & generate figures. I need Greek symbols in the legend and axis labels, including $\epsilon$. However, the resulting text doesn't distinguish between "normal" \epsilon and \varepsilon --- both of them appear as \varepsilon. Here's a minimal example:

import numpy as np
from pylab import *
import matplotlib.pyplot as plt

t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(t, s, 'k-', linewidth=2.0, label=r'$\epsilon$, $\varepsilon$, $\phi$, $\varphi$, $\sigma$, $\varsigma$')
plt.title(r'$\epsilon$, $\varepsilon$, $\phi$, $\varphi$, $\sigma$, $\varsigma$')
plt.xlabel(r'$t [M]$')
plt.ylabel(r'$\epsilon$, $\varepsilon$, $\phi$, $\varphi$, $\sigma$, $\varsigma$')
ax.legend(ncol=2, loc='lower left', fancybox=True)
plt.show()

When I process this on my Macbook (OS X El Capitan with Macports installations of TexLive and py27-matplotlib), everything renders correctly except the \epsilon.

ETA: the code does the right thing on a different machine (Scientific Linux).


Solution

  • You are not using TeX in your script. Matplotlib provides what is called MathText, which is a subset of LaTeX commands, rendered in normal UTF8 characters. This is how MathText looks like with the default fontset:

    enter image description here

    You can change the fontset to have "\varepsilon" look different than "\epsilon". However, it seems that out of the available fontsets, only "cm" has actually different symbols for those commands.

    plt.rcParams["mathtext.fontset"] = "cm"
    

    This will produce:

    enter image description here


    In order to have Latex used to render your text, you need to specifically tell matplotlib to do so. One option is to use

    plt.rcParams["text.usetex"] =True
    

    at the beginning of your script. This requires a working TeX installation.
    The example would then look like this, where "\varepsilon" and "\epsilon" are indeed different.

    enter image description here