如何调整Matplotlib中百分比格式坐标轴刻度标签的字体?
Matplotlib百分比轴刻度字体不一致问题解决
我常用以下配置让Matplotlib文本字体更美观:
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' matplotlib.rc('text', usetex = True)
但将某坐标轴设为百分比格式后,该轴刻度标签字体恢复为默认样式,Y轴与X轴字体呈现不一致的状态。
最小复现代码
import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' matplotlib.rc('text', usetex = True) from matplotlib import pyplot as py # 设置画布 figure = py.figure(figsize = (7.5, 5.0)) axs = [py.subplot(1, 1, 1)] # 绘制曲线 xs = np.linspace(0.0, np.pi, 100) ys = np.sin(xs) axs[0].plot(xs, ys, color = 'dodgerblue', label = r'$n = 1$') ys = np.sin(2.0 * xs) axs[0].plot(xs, ys, color = 'seagreen', label = r'$n = 2$') axs[0].axhline(0.0, color = 'gray', linestyle = 'dashed') # 设置Y轴为百分比格式 formatter = matplotlib.ticker.PercentFormatter(xmax = 1.0, decimals = 0, symbol = r'\%', is_latex = True) axs[0].yaxis.set_major_formatter(formatter) # 保存图片 name = 'test.pdf' py.tight_layout() py.savefig(name) py.close()
解决方法
问题根源是PercentFormatter即使设置了is_latex=True,生成的标签仍未正确继承全局LaTeX字体配置。可以通过以下两种方式修复:
方法1:强制刻度标签使用MathText
在设置完格式化器后,添加一行代码,强制Y轴刻度标签用LaTeX渲染:
axs[0].yaxis.set_tick_params(useMathText=True)
方法2:自定义LaTeX百分比格式化器
直接自定义一个格式化器,确保输出的标签是标准LaTeX格式,完全适配全局配置:
class LatexPercentFormatter(matplotlib.ticker.Formatter): def __init__(self, xmax=1.0, decimals=0): self.xmax = xmax self.decimals = decimals def __call__(self, x, pos=None): percentage = (x / self.xmax) * 100 return r'${:.{}f}\%$'.format(percentage, self.decimals) # 替换原有的PercentFormatter formatter = LatexPercentFormatter(xmax=1.0, decimals=0) axs[0].yaxis.set_major_formatter(formatter)
两种方法都能让Y轴刻度字体与X轴保持一致,使用全局配置的LaTeX字体。
内容的提问来源于stack exchange,提问作者zyy
相关产品推荐
相关产品推荐

