Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/17958485/matplotlib-not-using-latex-font-while-text-usetex-true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...