【问题标题】:Matplotlib: tick labels are inconsist with font setting (LaTeX text example)Matplotlib:刻度标签与字体设置不一致(LaTeX 文本示例)
【发布时间】:2017-04-06 07:21:42
【问题描述】:

我有以下简单的python代码:

import numpy as np
import matplotlib.pyplot as plt 

plt.rc( 'font', size=20, family="Times" )   # use a font with serifs

# the following line triggers the problem
plt.rc( 'text', usetex=True )               # activate LaTeX text rendering

fig = plt.figure( figsize=(8,6) )           # (width,height) in inches
ax1 = fig.add_subplot( 1, 1, 1 )            # rows cols plotnumber

ax1.plot( np.linspace(1,10,10), np.linspace(1,10,10)**2 )

ax1.set_xlabel( r'\textit{x} in a.u.' )
ax1.set_ylabel( r'\textit{y} in a.u.' )

plt.show()

结果如下图:

如您所见,与坐标轴标签相比,刻度标签的字体太细(或坐标轴标签太厚)。我发现这是由于激活了 LaTeX 文本渲染(参见代码中的注释),但我不知道如何更改它,因为我不想关闭 LaTeX 文本渲染。

知道为什么字体粗细(粗细的复数形式是什么?)不一致以及如何改变?

更新 1:根据 llap42 的建议,应该做一个 hack

plt.xticks([2, 4, 6, 8, 10], ['2', '4', '8', '10' ])

但这只是一种技巧,必须有更好的解决方案。

【问题讨论】:

  • 看起来 usetex 仅应用于标签。如果标签上有数字,它会更厚吗? (顺便说一句:厚度)
  • @ElmarPeise 标签中的数字越来越粗,所以usetex 也适用于数字
  • 对plt.rc() 的调用顺序是否重要?即您是否先尝试plt.rc('text', usetex=True),然后尝试plt.rc('font', size=20, family="Times")?
  • 问题是刻度标签不服从字体设置。尝试plt.rc('font',family = 'sans-serif', size=20) 时可以更好地看到这一点。正如can be seen,标签是无衬线的,但刻度标签不会改变。因此,与其询问“字体粗细”,不如将问题改写为为什么刻度标签不遵循字体设置。
  • 我在 matplotlib 页面上提出了一个问题:github.com/matplotlib/matplotlib/issues/8436

标签: python matplotlib tex


【解决方案1】:

正如 cmets 中所说,这是一个问题,即当与乳胶一起使用时,ticklabels 不遵守字体设置。

此问题似乎仅在使用 ScalarFormatter(这是轴的默认格式化程序)时发生。我已经在 GitHub 上发布了 an issue 的相关信息。

解决方法可能是使用不同的格式化程序。例如StrMethodFormatter:

import matplotlib.pyplot as plt 
import matplotlib.ticker

plt.rc( 'text', usetex=True ) 
plt.rc('font',family = 'sans-serif',  size=20)

fig , ax = plt.subplots(figsize=(5,3))

ax.set_xlabel( r'\textit{x} in a.u.' )
ax.set_ylabel( r'\textit{y} in a.u.' )

fmt = matplotlib.ticker.StrMethodFormatter("{x}")
ax.xaxis.set_major_formatter(fmt)
ax.yaxis.set_major_formatter(fmt)

plt.tight_layout()
plt.show()

【讨论】:

  • 是的,这行得通,也感谢您在 GitHub 上提出问题
  • 这可以以某种方式用于对数轴中的幂符号吗?
  • 谢谢!这个问题困扰了我一下午!
【解决方案2】:

另一种解决方案是将乳胶使用的字体设置为无衬线字体。 tex.stackexchange 解释了如何实现这一点。

一种解决方案是使用sfmath 乳胶包。要将其添加到序言中,请使用

    plt.rc('text.latex', preamble=r'\usepackage[cm]{sfmath}')

这也适用于other proposed solution 失败的对数刻度。

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2011-09-17
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多