2

In matplotlib, one can easily use latex script to label axes, or write legends or any other text. But is there a way to use new fonts such as 'script-r' in matplotlib? In the following code, I am labelling the axes using latex fonts.

import numpy as np
import matplotlib.pyplot as plt

tmax=10
h=0.01
number_of_realizations=6


for n in range(number_of_realizations):
    xpos1=0
    xvel1=0
    xlist=[]
    tlist=[]
    t=0
    while t<tmax:
        xlist.append(xpos1)
        tlist.append(t)
        xvel1=np.random.normal(loc=0.0, scale=1.0, size=None)
        xpos2=xpos1+(h**0.5)*xvel1                  # update position at time t
        xpos1=xpos2
        t=t+h
    plt.plot(tlist, xlist)
plt.xlabel(r'$ t$', fontsize=50)
plt.ylabel(r'$r$', fontsize=50)
plt.title('Brownian motion', fontsize=20)
plt.show()

It produces the following figure

normal r

But I want 'script-r' in place of normal 'r'. script r

In latex one has to add the following lines in preamble to render 'script-r'

\DeclareFontFamily{T1}{calligra}{}
\DeclareFontShape{T1}{calligra}{m}{n}{<->s*[2.2]callig15}{}

\DeclareRobustCommand{\sr}{%
\mspace{-2mu}%
\text{\usefont{T1}{calligra}{m}{n}r\/}%
\mspace{2mu}%
}

I don't understand how to do this in matplotlib. Any help is appreciated.

1 Answer 1

4

Matplotlib uses it's own hand-rolled (pure Python) implementation of TeX to do all of the math text stuff, so you absolutely cannot assume that what works in standard LaTeX will work with Matplotlib. That being said, here's how you do it:

  1. Install the calligra font so that Matplotlib can see it, then rebuild the font cache.

    • Lots of other threads deal with how to do this, I'm not going to go into detail, but here's some reference:
      • Use a font installed in a random spot on your filesystem.
      • How to install a new font into the Matplotlib managed font cache.
      • List all fonts currently known to your install of Matplotlib.
  2. Replace one of Matplotlib's TeX font families with your font of choice.

    • Here's a function I wrote a while ago that reliably does that:

      import matplotlib
      
      def setMathtextFont(fontName='Helvetica', texFontFamilies=None):
          texFontFamilies = ['it','rm','tt','bf','cal','sf'] if texFontFamilies is None else texFontFamilies
      
          matplotlib.rcParams.update({'mathtext.fontset': 'custom'})
          for texFontFamily in texFontFamilies:
              matplotlib.rcParams.update({('mathtext.%s' % texFontFamily): fontName})
      

      For you, a good way to use the function would be to replace the font used by \mathcal with calligra:

      setMathtextFont('calligra', ['cal'])
      
  3. Label your plots, for example, r'$\mathcal{foo}$', and the contents of the \math<whatever> macro should show up in the desired font.

    • Here's how you'd change your label-making code:

      plt.ylabel(r'$\mathcal{r}$', fontsize=50)
      

and that should do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.