Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default latex font in matplotlib

I want to use the the latex grammar like'$x^2$' in matplotlib for labels or annotations. But how to change the default font 'Roman' of latex to 'times new roman', without change anything else? Thank you

sorry for that i cannot upload a picture as a new user of this website.

I do not have latex installed on my computer and do not want to install one.

For example

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2
plt.rc('font', family='times new roman', size=16)
plt.plot(t, s)
plt.annotate('$Roman\ by\ TeX:\ x\ y$',(0.33,1.5))
plt.annotate('Times New Roman: x y', (0.33,1.4),style='italic')
plt.subplots_adjust(top=0.8)
plt.show()
like image 549
He Da Avatar asked Oct 20 '22 16:10

He Da


1 Answers

The default settings for LaTeX in matplotlib are set in your .matplotlibrc file. On Linux, this is in ~/.config/matplotlib/matplotlibrc, on other platforms it is in ~/.matplotlib/matplotlibrc (where ~ is your home directory). In this file are various options can control matplotlib behaviour.

The following setting determines whether you use LaTeX for all text in matplotlib (you probably don't want to turn this on, but may):

text.usetex        : false

This determines the family for the plots (serif shown here) and the font used for serif:

font.family        : serif
font.serif         : Times New Roman

The following determines what is used for math rendering (this is probably what you want). If you un-comment this line matplotlib will use the serif font defined above (currently Times) for rendering math:

mathtext.rm  : serif
mathtext.it  : serif:italic
mathtext.bf  : serif:bold
mathtext.fontset: custom

You can find more information about customising LaTeX in matplotlib in this documentation on the SciPy wiki. The font.serif setting allows you to change the serif font to anything you want. Unfortunately, it seems the matplotlib TeX engine will always use the Roman font if you ask for Times New Roman, see below:

Verdana:
Verdana

Arial:
Arial

Bitstream Vera Serif:
Bitstream Vera Serif

Times New Roman (actually displays Roman):
Times New Roman

As you can see the first three images are correct, but the final image is definitely not Times New Roman. Bitstream Vera Serif (second from bottom) may be sufficiently close in appearance if an alternative font is acceptable.

like image 193
mfitzp Avatar answered Nov 01 '22 08:11

mfitzp