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

Python虚拟环境中安装自定义字体:解决Matplotlib找不到Roboto问题

Matplotlib虚拟环境中无法识别RobotoCondensed字体的解决办法
  • 先修正字体名拼写错误
    你执行的代码里把字体后缀写成了.tft(正确是.ttf),而且findfont不需要带后缀,直接用字体家族名或正确文件名即可,比如改成:

    matplotlib.font_manager.findfont("RobotoCondensed")
    
  • 清除Matplotlib字体缓存
    虚拟环境下Matplotlib会生成本地字体缓存,哪怕你复制了字体,缓存没更新也识别不了。执行以下代码找到缓存目录:

    import matplotlib as mpl
    print(mpl.get_cachedir())
    

    找到输出的文件夹,删除里面所有fontlist-*.json格式的文件,然后重启Python环境。

  • 手动指定字体路径加载
    如果上面的方法没用,直接在代码里加载字体文件:

    from matplotlib.font_manager import FontProperties
    import matplotlib.pyplot as plt
    
    # 替换成你的RobotoCondensed字体绝对路径,比如Mac默认字体路径是~/Library/Fonts/
    font_path = "/Users/你的用户名/Library/Fonts/RobotoCondensed-Regular.ttf"
    roboto_font = FontProperties(fname=font_path)
    
    # 示例:用该字体绘制文本
    plt.text(0.5, 0.5, "测试RobotoCondensed字体", fontproperties=roboto_font, fontsize=16)
    plt.show()
    
  • 配置Matplotlib全局默认字体
    想全局使用该字体的话,修改Matplotlib配置文件:

    1. 找到虚拟环境中配置文件的位置:
      import matplotlib
      print(matplotlib.matplotlib_fname())
      
    2. 打开输出的matplotlibrc文件,修改以下两行(去掉前面的#注释):
      font.family: RobotoCondensed
      font.sans-serif: RobotoCondensed, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
      
    3. 同样需要清除字体缓存后重启环境生效。
  • 检查字体文件完整性
    确认你复制到虚拟环境字体文件夹的.ttf文件没有损坏,可在Mac字体册中打开该字体,验证是否能正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:45:33