【问题标题】:Matplotlib not using latex font while text.usetex==TrueMatplotlib 在 text.usetex==True 时不使用乳胶字体
【发布时间】:2013-07-31 06:38:01
【问题描述】:

我想使用 Latex 计算机现代字体为我的绘图创建标签。然而,说服 matplotlib 使用 Latex 字体的唯一方法是插入如下内容:

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

这当然很荒谬,我告诉latex 启动数学模式,然后暂时退出数学模式以写入实际字符串。如何确保所有标签都以乳胶呈现,而不仅仅是公式?我如何确保这将是默认行为?

一个最小的工作示例如下:

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()

这给出了以下结果:

这里的 x 轴是我希望标签出现的方式。如何确保所有标签都显示为这样,而无需进入数学模式并再次返回?

【问题讨论】:

  • 在我的系统上,默认行为是 usetex 为所有内容启用 LaTeX,实际上我正在寻找您描述的行为(LaTeX 仅适用于 $...$)。由于所有答案只提到必须如何设置 font.family 以实现您的情况,如果您可以指定实现这些非 LaTeX 字体的替代方案,那就太好了...

标签: python matplotlib latex


【解决方案1】:

我在 Mac OSX 上使用 matplotlib 1.3.1,在 matplotlibrc 中添加以下行对我有用

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

使用= 会导致UserWarning: Illegal line

【讨论】:

    【解决方案2】:

    默认情况下可以通过更改matplotlibrc文件中的几行来启用标记的答案:

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

    【讨论】:

      【解决方案3】:

      默认的 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()
      

      【讨论】:

      • 谢谢!这可以通过更改 matplotlibrc 文件默认启用。设置:tex.usetex = True font.family = serif font.serif = cm
      • 它可以工作,但我无法以 EPS 格式保存图(PNG 工作正常)。就我而言,我使用的是“Times”字体。它不完全相同但足够相似,并且 EPS 工作正常。
      • 或者,matplotlib.rcParams['font.family'] = 'serif'matplotlib.rcParams['font.serif'] = ['Computer Modern']
      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      相关资源
      最近更新 更多