Skip to content

Instantly share code, notes, and snippets.

@Junch
Last active July 29, 2025 10:50
Show Gist options
  • Select an option

  • Save Junch/de443b2c241b9b3463d359874a23a236 to your computer and use it in GitHub Desktop.

Select an option

Save Junch/de443b2c241b9b3463d359874a23a236 to your computer and use it in GitHub Desktop.
matplotlib汉字显示

1. 添加SimHei字体(simhei.ttf文件)

首先运行以下命令来查看matplotlib所在位置:

echo -e "import matplotlib\nprint(matplotlib.matplotlib_fname())" | python3

比如 /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc,将simhei.ttf拷贝到字体目录./matplotlib/mpl-data/fonts/ttf

2. 清除之前的缓存

查询得到缓存目录,然后清除这个目录

echo -e "import matplotlib\nprint(matplotlib.get_cachedir())" | python3

rm -rf ~/.matplotlib

3. 修改matplotlibrc文件或者在程序中指定字体

3.1 选项一:修改以下3个配置项 

这样处理后,代码中不再需要指定字体

font.family         : sans-serif
font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus  : False

3.1 选项二:在代码中指定字体

这个更灵活不需要修改配置文件

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

4. 验证

运行如下代码验证

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
#如果修改了配置文件,下面两行就不必要了
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

if __name__ == '__main__':
    plt.plot([-1,0,1,2,3])
    plt.title("天王盖地虎")
    plt.show()
  1. ttc字体文件也是可以使用的

ttc字体文件也是可以使用的,但需要修改matplotlib/font_manager.py文件。在函数get_fontext_synonyms中添加'ttc'这一选项。

def get_fontext_synonyms(fontext):
    """
    Return a list of file extensions extensions that are synonyms for
    the given file extension *fileext*.
    """
    return {'ttf': ('ttf', 'otf', 'ttc'),
            'otf': ('ttf', 'otf'),
            'afm': ('afm',)}[fontext]

具体可以参考Matplotlib在Mac上的中文支持問題

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment