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

如何在Google Colab的Matplotlib中全局使用Arial字体?

在Google Colab中全局设置Matplotlib图表字体为Arial的可行方案

解决步骤

  • 1. 安装Arial系统字体
    Colab默认Ubuntu环境不含Arial字体,直接通过系统包管理器安装:
!apt-get install -y fonts-arial
  • 2. 重建Matplotlib字体缓存
    Matplotlib会缓存已识别的字体,安装新字体后需重建缓存让其识别:
import matplotlib.font_manager as fm
fm._rebuild()

(如果仍不生效,可以尝试执行!rm ~/.cache/matplotlib -rf删除缓存目录,然后重启Colab内核)

  • 3. 全局配置Matplotlib字体参数
    设置全局字体为Arial,同时可按需调整字号等属性适配期刊要求:
import matplotlib.pyplot as plt
plt.rcParams.update({
    'font.family': 'Arial',
    'font.size': 12,
    'axes.labelsize': 12,
    'axes.titlesize': 14,
    'xtick.labelsize': 10,
    'ytick.labelsize': 10
})

验证方案

运行以下代码测试字体是否生效:

plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.title('Test Plot')
plt.show()

此时图表所有文字应使用Arial字体,且无字体找不到的警告。

常见失败原因说明

之前使用wget下载字体后未正确安装到系统字体目录,或未清除Matplotlib缓存,导致字体无法被识别。通过系统包管理器安装字体可直接写入系统默认字体路径,配合缓存重建能确保Matplotlib正确加载Arial。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:02:32