matplotlib图标有中文时报错

这个错误是因为 matplotlib 的默认字体(通常是 DejaVu Sans)不包含中文字符,导致无法正确显示中文。以下是几种解决方法:


方法1:指定支持中文的字体

import matplotlib.pyplot as plt

# 设置支持中文的字体(如SimHei、Microsoft YaHei等)
plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows系统
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # Mac系统
# plt.rcParams['font.sans-serif'] = ['Noto Sans CJK JP']  # Linux系统(需安装)

# 解决负号显示问题
plt.rcParams['axes.unicode_minus'] = False  

# 现在绘图时中文能正常显示
df.plot(x='年份', y='销售额', title='中文标题示例')
plt.show()

方法2:直接指定字体路径

如果系统中已安装中文字体(如 .ttf 文件),可以明确指定路径:

from matplotlib import font_manager

# 指定字体文件路径(示例路径,需替换为实际路径)
font_path = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"  
font_prop = font_manager.FontProperties(fname=font_path)

# 绘图时通过fontproperties参数指定
df.plot(x='年份', y='销售额', title='中文标题')
plt.title('中文标题', fontproperties=font_prop)
plt.show()

方法3:安装中文字体(适用于Linux服务器)

如果系统缺少中文字体(如Jupyter Notebook运行在Linux服务器上):

  1. 安装字体(以Noto Sans CJK为例):
    sudo apt install fonts-noto-cjk  # Debian/Ubuntu
    # 或
    sudo yum install google-noto-sans-cjk-ttc-fonts  # CentOS/RHEL
    
  2. 清除matplotlib缓存:
    rm -rf ~/.cache/matplotlib
    
  3. 在代码中设置字体:
    plt.rcParams['font.sans-serif'] = ['Noto Sans CJK JP']
    

方法4:使用系统默认字体(跨平台)

import matplotlib.pyplot as plt
import platform

# 根据操作系统自动选择字体
if platform.system() == 'Windows':
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
elif platform.system() == 'Darwin':  # Mac
    plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
else:  # Linux
    plt.rcParams['font.sans-serif'] = ['Noto Sans CJK JP']

plt.rcParams['axes.unicode_minus'] = False

验证是否生效

import matplotlib.font_manager as fm
# 查看当前可用字体列表
[f.name for f in fm.fontManager.ttflist if 'CJK' in f.name or 'Hei' in f.name]

选择适合你系统环境的方法后,中文标题、标签等应能正常显示,不再报 Glyph missing 错误。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容