Mac OS上使用matplotlib库显示中文字体

问题描述

如果我们想要使用matplotlib画图的话,可能会出现下面的这种warning:

UserWarning: Glyph 24212 (\N{CJK UNIFIED IDEOGRAPH-5E94}) missing from current font.

解决步骤

解决这个问题,可以按照下面的做法来实现:
1.首先找到matplotlib库字体在那里。

import matplotlib
print(matplotlib.matplotlib_fname())

例如我这里得到的地址就是

/Users/user_name/miniforge3/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc

我们就需要进入到matplotlibrc上一级目录即可

/Users/user_name/miniforge3/lib/python3.9/site-packages/matplotlib/mpl-data/

找到这里面的fonts文件夹。进入后,再进入到ttf文件夹
2. 在这个字体网址中找到你需要下载的字体。例如我这里需要下载宋体,就需要搜索SimSun,然后下载即可。至于,我们想找的字体的英文名字是什么,可以去这个字体名字上看。
3. 将下载好的SimSun.tff文件放在上面提到的/Users/user_name/miniforge3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf文件夹中。就像下面这个样子
在这里插入图片描述
4. 然后修改下面这个文件路径的内容。这个路径就是你在步骤1中获得的地址(和我下面的这个不一样的)。为了保险起见,你可以先备份这个文件一份。

/Users/user_name/miniforge3/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc

需要修改的内容有:
a. 你搜索我下面图中箭头所指的关键词,然后加入你刚刚下载的字体名称。就像我下载的是SimSun.tff,所以在下面两处中加入的就是SimSun
在这里插入图片描述
b. 为了防止中文的 - 出现乱码,需要修改下面的内容。本来axes.unicode_mius: True,现在需要将其修改为False.
在这里插入图片描述
5. 然后输入下面的代码,刷新matplotlib的字体缓存

import shutil
import matplotlib
shutil.rmtree(matplotlib.get_cachedir())

执行完毕后,就可以使用matplotlib库来显示中文了。使用下面的代码就可以使用宋体了。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimSun']

参考文章

中文字体的英文名称 (simhei, simsun) 宋体 微软雅黑
Mac OS系统下实现python matplotlib包绘图显示中文(亲测有效)
module ‘matplotlib.font_manager‘ has no attribute ‘_rebuild‘解决方法

相关推荐

  1. 解决matplotlib中文显示乱码

    2024-03-31 20:28:06       45 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-31 20:28:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-31 20:28:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-31 20:28:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-31 20:28:06       20 阅读

热门阅读

  1. map net收集

    2024-03-31 20:28:06       15 阅读
  2. MongoDB聚合运算符:$literal

    2024-03-31 20:28:06       15 阅读
  3. Qt之创建向导用户界面QWizard

    2024-03-31 20:28:06       17 阅读
  4. ubuntu22.04安装Fcitx5的步骤

    2024-03-31 20:28:06       16 阅读
  5. python中的re库 ,正则表达式模块

    2024-03-31 20:28:06       17 阅读
  6. 3.30蓝桥杯备赛写题心得

    2024-03-31 20:28:06       18 阅读
  7. vue知识点: v-if和v-for为何不能同时使用?

    2024-03-31 20:28:06       14 阅读
  8. Ansible

    Ansible

    2024-03-31 20:28:06      15 阅读
  9. Spark GraphX 算法实例

    2024-03-31 20:28:06       16 阅读