python - Matplotlib:刻度标签与字体设置不一致(LaTeX 文本示例)

标签 python matplotlib tex

我有以下简单的 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()

结果如下图: Font thickness in tick-labels wrong

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

知道为什么字体粗细(粗细的复数是多少?)不一致以及如何更改它?

更新 1:遵循 llap42 的建议, 一个黑客会做

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

但这只是一个 hack,必须有更好的解决方案。

最佳答案

正如评论中所说,这是一个与 latex 一起使用时刻度标签不遵守字体设置的问题。

这个问题似乎只在使用 ScalarFormatter(这是轴的默认格式化程序)时才会发生。我已经发布了 an issue关于这个在 GitHub 上。

解决方法可能是使用不同的格式化程序。例如 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()

enter image description here

关于python - Matplotlib:刻度标签与字体设置不一致(LaTeX 文本示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43248336/

相关文章:

matplotlib - 为 seaborn PairGrid 设置不同的轴范围

python - 用另一列的值替换字符串的一部分

python - Firebase Cloud Functions Python - 无法添加依赖项

python - Pandas 错误 - 为什么我的对象是混合类型?

django - Mod_wsgi工作进程段错误(11)

python - 如何删除 x 轴的垂直线并向绘图子图添加标签?

python - 如何在 Google App Engine 上使用 MathJax 库

latex - 在 Latex 文件的每一页上创建指向特定页面的链接

LaTeX:重新定义星号命令

python - 如何使用 opengl/pyglet 在 python 中绘制/使用像素并更改该像素的大小?