matplotlib 中文显示设置

环境

Python 3.6, matplotlib 3, Linux

方法1:

  1. 查找或拷贝字体文件到 matplotlib 库的 fonts 目录.
    例如微软雅黑字体: /.../python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/msyh.ttf
  2. 删除 ~/.cache/matplotlib 的 cache 目录.
  3. 设置字体
import matplotlib.pyplot as pyplot
pyplot.rcParams['font.family'] = ['sans-serif']
pyplot.rcParams['font.sans-serif'] = ['MicroSoft YaHei']

方法2: FontProperties

from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc")
foo.foo_func(, prop=my_font)
or
foo.foo_func(, fontproperties=font)

这种方法比较不优雅, 临时或测试可以用用.

其他

查询 matplotlibrc 配置文件的位置:

import matplotlib
matplotlib.matplotlib_fname()
'/.../python3.6/site-packages/matplotlib/mpl-data/matplotlibrc'

查询使用字体的位置和信息:

from matplotlib.font_manager import findfont, FontProperties
findfont(FontProperties(family=FontProperties().get_family()))
pyplot.rcParams['font.family']
pyplot.rcParams['font.sans-serif']

doc

Configuring the font family
Customizing Matplotlib with style sheets and rcParams