Python Matplotlib 在 text.usetex==True 时不使用乳胶字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17958485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib not using latex font while text.usetex==True
提问by Dirklinux
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:
我想用乳胶计算机现代字体为我的图创建标签。但是,说服 matplotlib 使用乳胶字体的唯一方法是插入如下内容:
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:
这给出了以下结果:
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?
这里的 x 轴是我希望标签出现的方式。如何确保所有标签都像这样显示,而不必进入数学模式并再次返回?
采纳答案by Greg
The default Latex font is known as Computer Modern
:
默认的 Latex 字体称为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()
回答by Dirklinux
The marked answer can be enabled by default by changing a few lines in the matplotlibrc
file:
默认情况下,可以通过更改matplotlibrc
文件中的几行来启用标记的答案:
text.usetex = True
font.family = serif
font.serif = cm
回答by CyLiu
I am using matplotlib 1.3.1 on Mac OSX, add the following lines in matplotlibrc
works for me
我在 Mac OSX 上使用 matplotlib 1.3.1,在matplotlibrc
我的作品中添加以下几行
text.usetex : True
font.family : serif
font.serif : cm
Using =
leads to a UserWarning: Illegal line
使用=
导致UserWarning: Illegal line