You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用本地TTF文件设置Matplotlib色条及刻度标签字体?

解决方法

可以用FontProperties加载本地TTF文件,统一设置所有需要的文本元素字体,包括色条标签、坐标轴刻度、色条刻度,步骤如下:

  1. 导入FontProperties类
  2. 用本地TTF文件路径创建FontProperties对象
  3. 分别设置坐标轴刻度、色条标签和色条刻度的字体

修改后的完整代码:

from matplotlib.font_manager import FontProperties
from pathlib import Path
import matplotlib.pyplot as plt

def plot(example_param1, example_param2):
    fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(12, 6))

    # 加载本地字体文件
    fpath = Path('Arial Nova.ttf')
    font_prop = FontProperties(fname=str(fpath))

    surf = ax.plot_trisurf(distances.flat, temperatures.flat, function(
        example_param1, 
        example_param2
    ).flat, cmap='coolwarm')
    
    # 获取色条对象并设置字体
    cbar = fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
    # 设置色条标签字体
    cbar.set_label('deviation (mm)', fontproperties=font_prop)
    # 设置色条刻度字体
    cbar.ax.tick_params(fontproperties=font_prop)  # 可添加labelsize参数调整字号

    # 设置坐标轴标签字体
    ax.set_xlabel('position in span (m)', fontproperties=font_prop)
    ax.set_ylabel('temperature (°C)', fontproperties=font_prop)
    ax.set_zlabel('z-axis label', fontproperties=font_prop)  # 若有z轴标签可按需设置

    # 设置坐标轴刻度字体
    ax.set_xticklabels(ax.get_xticklabels(), fontproperties=font_prop)
    ax.set_yticklabels(ax.get_yticklabels(), fontproperties=font_prop)
    ax.set_zticklabels(ax.get_zticklabels(), fontproperties=font_prop)

    ax.view_init(elev=30, azim=160)
    plt.show()

关键说明

  • FontProperties是Matplotlib专门用于管理字体的类,通过fname参数直接传入本地TTF文件路径,避开系统字体查找的问题
  • 色条对象(cbar)的标签通过set_label的fontproperties参数设置,刻度则通过cbar.ax.tick_params指定字体
  • 坐标轴刻度需要先获取现有刻度标签,再用set_xticklabels等方法传入fontproperties参数

内容的提问来源于stack exchange,提问作者am1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:30:02