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

Matplotlib:Python 3.9云函数中使用Balthazar自定义字体的方法

Google Cloud Functions Python 3.9 环境配置Matplotlib自定义Balthazar字体方案

步骤1:调整项目文件结构

先将Balthazar字体的ttf格式文件存放到云函数项目根目录下的fonts文件夹中,最终项目结构参考:

云函数项目根目录/
├── main.py
├── requirements.txt
└── fonts/
    └── Balthazar-Regular.ttf

步骤2:配置依赖文件

在requirements.txt中添加Matplotlib依赖,版本适配Python 3.9即可:

matplotlib>=3.4.0

步骤3:代码内动态加载字体

Google Cloud Functions为无状态运行环境,无法提前在系统层面安装字体,直接通过Matplotlib的字体管理器动态加载本地字体文件即可,无需额外环境配置,示例代码如下:

import matplotlib.pyplot as plt
from matplotlib import font_manager
import os

def 你的云函数入口(request):
    # 加载本地存放的Balthazar字体
    font_path = os.path.join(os.getcwd(), "fonts", "Balthazar-Regular.ttf")
    balthazar_font = font_manager.FontProperties(fname=font_path)

    # 你的绘图逻辑,可替换为散点图相关代码
    fig, ax = plt.subplots()
    ax.scatter([1,2,3,4,5,6], [0,0.2,0.4,0.6,0.8,1])

    # 调用自定义字体绘制文字
    ax.text(6, 0.5, 'Test', fontproperties=balthazar_font, fontsize=20)

    # 后续图表保存、返回逻辑
    # ...
    plt.close()
    return "图表生成完成"

如果你需要全图表默认使用该字体,可在加载字体后添加全局配置:

plt.rcParams["font.family"] = balthazar_font.get_name()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:36:02