我有以下简单的 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 的建议, 一个黑客会做
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()
关于python - Matplotlib:刻度标签与字体设置不一致(LaTeX 文本示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43248336/