引言

日常工作中,在 python 中使用 matplotlibseaborn 画图时,如果有中文字符的话,在图像中会变成 ,导致图片无法直观的表达数据,反而还会造成疑惑。笔者将就画图时如何正常显示中文字体,列举几种可选的办法,诸位按需取用。

方案一:使用系统字体

python 用户在安装 matplotlibseaborn 时其实都安装了很多字体,根据 matplotlib 默认的配置文件 YOUR_PYTHON_PATH/site-packages/matplotlib/mpl-data/matplotlibrc 中的内容可知,画图时默认的字体为 sans-serif,主要为以下字体:

matplotlibrc.png

在安装包时,包中也都有这些字体,但这些字体好像都不支持中文,所以如果想支持中文,那么必须要安装支持中文的字体,或者直接使用电脑系统的中文字体。

matplotlibrc.png

通常情况下,可以直接设置图像显示字体为黑体 SimHei ,在大部分电脑中都有这个字体。

import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["SimHei"] #设置字体
plt.rcParams["axes.unicode_minus"] = False #该语句解决图像中的“-”负号的乱码问题

但也存在少部分电脑中没有 SimHei 这个字体的情况,此时可以考虑系统中其他可用的中文字体,通过如下代码可以将 matplotlib 中的已有的全部字体打印出来:

# 引入 matplotlib 的字体管理器
from matplotlib import font_manager

for font in font_manager.fontManager.ttflist:
    # 寻找字体文件路径中存在 kai 的字体
    if "kai" in font.fname.lower():
        # 将字体名称打印
        print(font.name)
matplotlibrc.png

然后在字体管理器中找一款能支持中文的字体,将对应的字体名设置为 matplotlib 的字体即可。

import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["Kaiti SC"] #设置字体
plt.rcParams["axes.unicode_minus"] = False #该语句解决图像中的“-”负号的乱码问题

设置完成字体后,即可正常显示中文。

combine_rules_kaiti_sc.svg

方案二:使用离线字体文件

matplotlib 有字体管理器 font_manager ,可以通过字体管理器添加离线字体到 matplotlib 的字体库中,再设置对应的字体名即可调整 matplotlib 的字体。

import matplotlib.pyplot as plt
from matplotlib import font_manager # 引入 matplotlib 的字体管理器


# 添加离线字体文件到 matplotlib 的字体库中
font_path = "/Users/lubberit/Desktop/workspace/pdtr/pdtr/matplot_chinese.ttf"
font_manager.fontManager.addfont(font_path)

# 获取离线字体的字体名称
font_name = font_manager.FontProperties(fname=font_path).get_name()

# 设置 matplotlib 字体为加载的离线字体
plt.rcParams['font.family'] = font_name
plt.rcParams['axes.unicode_minus'] = False

设置字体后即可支持中文显示。

combine_rules_kaiti_sc.svg

参考文件

https://matplotlib.org/stable/api/font_manager_api.html#module-matplotlib.font_manager