Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib not using latex font while text.usetex==True

I want to create labels to my plots with the latex computer modern font. However, the only way to persuade matplotlib to use the latex font is by inserting something like:

title(r'$\mathrm{test}$') 

This is of course ridiculous, I tell latex to start math mode, and then exit math mode temporary to write the actual string. How do I make sure that all labels are rendered in latex, instead of just the formulas? And how do I make sure that this will be the default behaviour?

A minimal working example is as follows:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np  # use latex for font rendering mpl.rcParams['text.usetex'] = True   x = np.linspace(-50,50,100) y = np.sin(x)**2/x plt.plot(x,y)  plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$') plt.ylabel(r'Not a latex font') plt.show() 

This gives the following result:

Plot showing incorrect rendering of latex font types

Here the x axis is how I want the labels to appear. How do I make sure that all labels appear like this without having to go to math mode and back again?

like image 829
Dirklinux Avatar asked Jul 30 '13 22:07

Dirklinux


People also ask

How do I enable LaTeX in matplotlib?

Matplotlib can use LaTeX to render text. This is activated by setting text. usetex : True in your rcParams, or by setting the usetex property to True on individual Text objects.

What is the default font in matplotlib?

The default font has changed from "Bitstream Vera Sans" to "DejaVu Sans".

What is the default LaTeX font?

LaTeX's default font is Computer Modern, but the editor also supports a number of other font types. Refer to the LaTeX font catalogue to see the range of fonts offered by LaTeX and how to use them in your document. To italicize text, use the \textit{..}


2 Answers

The default Latex font is known as Computer Modern:

from matplotlib import rc import matplotlib.pylab as plt  rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True)  x = plt.linspace(0,5) plt.plot(x,plt.sin(x)) plt.ylabel(r"This is $\sin(x)$", size=20) plt.show() 

enter image description here

like image 87
Greg Avatar answered Oct 04 '22 09:10

Greg


I am using matplotlib 1.3.1 on Mac OSX, add the following lines in matplotlibrc works for me

text.usetex : True font.family : serif  font.serif  : cm 

Using = leads to a UserWarning: Illegal line

like image 41
CyLiu Avatar answered Oct 04 '22 08:10

CyLiu