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

Matplotlib绘图设置Times New Roman字体报错,求问题原因及解决步骤

Matplotlib使用Times New Roman字体报错的问题分析与解决

错误原因

  1. 参数格式错误:mpl.rcParams["font.serif"] 要求传入字体名称列表,而你直接赋值了单个字符串"Times New Roman",导致Matplotlib无法正确匹配serif字体族的备选字体规则。
  2. 系统无对应字体或未被识别:你的系统可能没有安装Times New Roman,或者Matplotlib的字体管理器未检测到该字体(比如刚安装字体但未刷新缓存)。

解决步骤

  • 修正配置参数格式
    将字体配置改为列表形式,保留备选字体避免找不到目标字体时出错:

    import matplotlib as mpl
    mpl.rcParams["font.family"] = "serif"
    # 列表形式,优先用Times New Roman,找不到则用备选 serif 字体
    mpl.rcParams["font.serif"] = ["Times New Roman", "DejaVu Serif", "serif"]
    
  • 确认系统已安装Times New Roman

    • Windows系统默认自带,无需额外安装;
    • Linux(如Ubuntu)可通过命令安装微软核心字体:
      sudo apt update && sudo apt install ttf-mscorefonts-installer
      
    • macOS可通过「字体册」添加该字体(可从Windows系统复制ttf文件,或使用正版字体文件)。
  • 刷新Matplotlib字体缓存
    如果刚安装字体,需让Matplotlib重新识别:

    1. 手动删除Matplotlib的字体缓存文件:
      • Windows:C:\Users\<你的用户名>\.matplotlib\fontlist-*.json(*为版本号,如v330)
      • Linux/macOS:~/.cache/matplotlib/fontlist-*.json
    2. 或者在代码中强制重建缓存(注意这是内部函数,仅临时使用):
      import matplotlib.font_manager as fm
      fm._rebuild()
      
  • 直接指定字体文件(备选方案)
    如果全局配置仍不生效,可手动指定字体文件路径:

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    
    # 替换为你的Times New Roman字体文件路径
    font_prop = FontProperties(fname="C:/Windows/Fonts/times.ttf")  # Windows示例路径
    plt.pie(data)
    plt.title('Piechart', fontproperties=font_prop)
    # 若要让饼图标签、图例也用该字体,需对应设置fontproperties参数
    plt.legend(prop=font_prop)
    plt.show()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:17:52