如何在Matplotlib简易图表中设置主次刻度的字体大小与粗细?
Matplotlib刻度字体与自定义字体设置解决方案
针对你提出的三个问题,逐一给出具体实现方法:
1. 主次刻度标签的字体大小与粗细设置
可以通过set_tick_params()的which参数区分主刻度(major)和次刻度(minor),再用fontweight参数设置字体粗细(可选值如'bold'、'normal'等),labelsize指定字体大小(单位pt)。
示例代码片段:
# 设置主刻度字体:大小12pt,加粗 ax.xaxis.set_tick_params(which='major', labelsize=12, fontweight='bold') ax.yaxis.set_tick_params(which='major', labelsize=12, fontweight='bold') # 设置次刻度字体:大小10pt,常规粗细 ax.xaxis.set_tick_params(which='minor', labelsize=10, fontweight='normal') ax.yaxis.set_tick_params(which='minor', labelsize=10, fontweight='normal')
2. 除set_tick_params外,用Formatters设置字体参数
不是只能用set_tick_params(),Formatters也可以实现字体参数设置,主要有两种方式:
方法1:通过刻度标签对象直接设置
# 获取x轴主刻度标签并设置字体属性 for label in ax.get_xticklabels(which='major'): label.set_fontsize(12) label.set_fontweight('bold') # 获取y轴次刻度标签并设置字体属性 for label in ax.get_yticklabels(which='minor'): label.set_fontsize(10) label.set_fontfamily('monospace')
方法2:结合自定义Formatter设置
如果使用自定义Formatter生成刻度标签,可在生成后给标签绑定字体属性:
from matplotlib.ticker import FuncFormatter def format_x_ticks(x, pos): return f'{x:.1f}' # 创建Formatter并关联到x轴 formatter = FuncFormatter(format_x_ticks) ax.xaxis.set_major_formatter(formatter) # 给该Formatter对应的刻度标签设置字体 for label in ax.get_xticklabels(): label.set_fontweight('bold')
3. 使用自定义字体"Source Code Pro"
方式1:调用已安装的系统字体
如果字体已在系统中安装,可直接通过字体名称调用:
# 全局设置(对图表所有文本生效) plt.rcParams['font.family'] = 'Source Code Pro' # 或仅对刻度标签单独设置 ax.xaxis.set_tick_params(which='major', labelsize=12, fontfamily='Source Code Pro')
方式2:指定本地字体文件路径
如果字体未系统安装,可通过FontProperties加载本地字体文件:
from matplotlib.font_manager import FontProperties # 加载指定路径的字体文件 font_path = '/path/to/SourceCodePro-Regular.ttf' custom_font = FontProperties(fname=font_path, size=12) # 应用到刻度标签 for label in ax.get_xticklabels(which='major'): label.set_fontproperties(custom_font) # 或通过set_ticklabels间接绑定 ax.set_yticklabels(ax.get_yticks(), fontproperties=custom_font)
整合所有设置的完整MWE
import numpy as np from matplotlib import pyplot as plt import matplotlib.ticker as ticker from matplotlib.font_manager import FontProperties x = np.linspace(0, 10, 1000) y = x**2 z = 1 + 5*x # Plotting: fig, ax = plt.subplots() ax.plot(x, y, color='blue', linewidth=2.0, label="Quadratic") ax.plot(x, z, color='orange', linestyle='-.', linewidth=1.5, label="Linear") # Axis limits ax.set_xlim(0, 10) ax.set_ylim(0, 100) # Axis labels ax.set_xlabel(r"A linear array of $X$ values", fontsize=16) ax.set_ylabel(r"Some functions $y(x)$", fontsize=16) # Ticks: ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.yaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.xaxis.set_minor_formatter(ticker.ScalarFormatter()) # 设置主次刻度字体大小与粗细 ax.xaxis.set_tick_params(which='major', labelsize=12, fontweight='bold') ax.yaxis.set_tick_params(which='major', labelsize=12, fontweight='bold') ax.xaxis.set_tick_params(which='minor', labelsize=10, fontweight='normal') ax.yaxis.set_tick_params(which='minor', labelsize=10, fontweight='normal') # 启用自定义字体(取消注释并替换路径) # custom_font = FontProperties(fname='/path/to/SourceCodePro-Regular.ttf', size=12) # for label in ax.get_xticklabels() + ax.get_yticklabels(): # label.set_fontproperties(custom_font) ax.set_title("Some simple plots", loc='left') ax.legend(frameon=False) plt.show()
内容的提问来源于stack exchange,提问作者user136555
相关产品推荐
相关产品推荐

