【问题标题】:Consistent fonts between matplotlib and latexmatplotlib 和 latex 字体一致
【发布时间】:2016-02-29 18:14:39
【问题描述】:

我正在拼命寻找“最简单的方法”来在我的 matplotlib 图形和我的 Latex 文档中获得外观相同的文本。

到目前为止,我的策略是:

  • 为我的 Latex 图形设置明确的宽度,并使用 Matplotlib 设置相同的大小。这样,将 mpl 中的字体大小设置为等于 Latex 字体大小应该是第一步

  • 在 mpl 中使用 usetex = True 选项。我知道这应该使 mpl 使用 Latex 进行图中的所有文本处理(标题、标签、文本、注释等)。

我的问题是到最后我还是无法设置我想要的字体。

这是一个示例,其中水平轴标签字体与刻度标签明显不同,我确信这与我的乳胶文档的文本相同。

这是生成该图的代码:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

with plt.style.context('journal'):
  fig_size = [3.4, 2.1]
  fig = plt.figure(1, figsize=fig_size)
  ax1 = plt.subplot(111)
  ax1.plot([1,2,3,4,5], '+--')
  ax1.set_xlabel(r'1 2 3 4.0 intensity [$10^{13}p$]')
  plt.tight_layout()
  fig.savefig('test.png') # I saved to png for SO but the goal is eps

我的journal mpl 样式表是

backend: PS
text.usetex: True
text.latex.unicode: True
font.family: lmodern # apparently no effect as usetex is true anyway
font.size: 10
axes.titlesize: 10
axes.labelsize: 10
axes.unicode_minus: True
axes.linewidth: 1
legend.fontsize: 10
xtick.labelsize: 10
xtick.major.size: 4
xtick.major.width: 0.5
ytick.labelsize: 10
lines.linewidth: 1.5
lines.markersize: 3
figure.titleweight: normal
savefig.dpi: 600

此外,我什至不确定我是否能够从计算机现代选择/切换到拉丁现代,部分原因是我的眼睛无法区分它们(这在某种程度上使这个问题无关紧要,但你知道。 .. 极客...)。

【问题讨论】:

  • 我发布的答案似乎可以解决我的问题,但我仍然很想“一般”地对我的问题提供反馈。

标签: python matplotlib fonts


【解决方案1】:

我多年来一直在使用它,没有任何问题;只需在 text.latex preamble 中指定与我在 LaTeX 文档中使用的字体相同的字体,例如:

import matplotlib.pylab as pl
from matplotlib import rc
rc('text', usetex=True)
rc('font', size=14)
rc('legend', fontsize=13)
rc('text.latex', preamble=r'\usepackage{cmbright}')

pl.figure()
pl.plot([0,1], [0,1], label=r'$\theta_{\phi}^3$')
pl.legend(frameon=False, loc=2)
pl.xlabel(r'change of $\widehat{\phi}$')
pl.ylabel(r'change of $\theta_{\phi}^3$')

edit 我以前从未使用过样式表,但是当我将它放入一个空的样式表中时,这似乎也可以:

text.usetex: True
font.size: 14
legend.fontsize: 13
text.latex.preamble: \usepackage{cmbright}

【讨论】:

  • 我很高兴它就这么简单,同时我也很沮丧,以至于我花了一个下午的时间...
  • 你知道如何在样式表中指定它吗?
  • 直到今天我才知道 matplotlib 有/有样式表 :)
  • 它似乎与样式表一起工作,我已经更新了答案
【解决方案2】:

似乎出于某种疯狂的原因,字体被切换到了New Century School Book。见this SO answer

我仍然不确定发生了什么,但似乎font.serif 选项的存在 会改变行为,无论font.familyfont.serif 中的实际内容如何。这是一个示例(问题中的其他选项):

backend: PS
text.usetex: True
text.latex.unicode: True
font.family: xyzxyz
font.serif: abcabc # Comment this out

这给出了以下内容,其中轴标签使用与刻度标签相同的字体。注释掉 font.serif 行会生成初始问题的情节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    相关资源
    最近更新 更多