Alf*_*Alf 6 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()
Run Code Online (Sandbox Code Playgroud)
如您所见,与轴标签相比,刻度标签的字体太薄(或者轴标签太厚)。我发现这是由于激活了 LaTeX 文本渲染(请参阅代码中的注释),但我不知道如何更改它,因为我不想关闭 LaTeX 文本渲染。
知道为什么字体厚度(厚度的复数是什么?)不一致以及如何更改?
更新 1:按照llap42的建议,可以进行 hack
plt.xticks([2, 4, 6, 8, 10], ['2', '4', '8', '10' ])
Run Code Online (Sandbox Code Playgroud)
但这只是一个黑客,必须有更好的解决方案。
正如评论中所说,这是一个刻度标签在与乳胶一起使用时不遵守字体设置的问题。
这个问题似乎只在使用 a ScalarFormatter(这是轴的默认格式化程序)时发生。我已经在 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()
Run Code Online (Sandbox Code Playgroud)