如何将Python绘图字体设为TeX字体同时保留刻度标签为普通字体
解决方案
你可以通过拆分字体配置规则、覆盖对数刻度的格式化器实现需求,两种常用方案如下:
方案1:不开启全局LaTeX渲染,单独指定非刻度文本使用Computer Modern字体
这种方式不需要启用text.usetex,避免全局影响刻度标签:
import matplotlib.pyplot as plt from matplotlib import rcParams # 全局设置非刻度文本默认使用Computer Modern字体 rcParams["font.family"] = "serif" rcParams["font.serif"] = ["Computer Modern Roman"] + rcParams["font.serif"] # 单独设置刻度标签使用Python默认无衬线字体 plt.rcParams['xtick.labelfamily'] = 'DejaVu Sans' plt.rcParams['ytick.labelfamily'] = 'DejaVu Sans' # 对数刻度绘图示例 fig, ax = plt.subplots() ax.set_xscale("log") ax.set_yscale("log") # 标题、坐标轴标签会自动使用Computer Modern字体 ax.set_xlabel("X轴标签") ax.set_ylabel("Y轴标签") ax.set_title("绘图标题") plt.show()
方案2:已开启全局text.usetex的场景,手动覆盖对数刻度格式化器
如果你已经全局开启了LaTeX渲染,只需要修改对数刻度的格式化器,强制数字在文本模式输出即可:
import matplotlib.pyplot as plt from matplotlib import rcParams from matplotlib.ticker import LogFormatterSciNotation # 你当前使用的全局LaTeX字体配置 rcParams["text.usetex"] = True rcParams["font.family"] = "serif" rcParams["font.serif"] = ["Computer Modern Roman"] # 自定义对数刻度格式化器,返回纯文本格式的数字,不进入数学模式 class PlainLogFormatter(LogFormatterSciNotation): def __call__(self, x, pos=None): return f"{x:g}" # 对数刻度绘图示例 fig, ax = plt.subplots() ax.set_xscale("log") ax.set_yscale("log") # 给x、y轴应用自定义格式化器 ax.xaxis.set_major_formatter(PlainLogFormatter()) ax.yaxis.set_major_formatter(PlainLogFormatter()) ax.set_xlabel("X轴标签") ax.set_ylabel("Y轴标签") ax.set_title("绘图标题") plt.show()
如果你使用的是Matplotlib 3.5及以上版本,也可以直接通过
ax.tick_params参数单独指定刻度标签的字体属性,不需要自定义格式化器。
内容的提问来源于stack exchange,提问作者opisthofulax
相关产品推荐
相关产品推荐

