ubuntu中解决matplotlib无法显示中文问题

一、查看本机matplotlib中支持的字体

运行下列代码即可查看支持的字体

python 复制代码
# 查询当前系统所有字体
from matplotlib.font_manager import FontManager

# 获取字体名称集合
mpl_fonts = sorted(set(f.name for f in FontManager().ttflist))

# 设置每行列数
cols = 5
font_rows = [mpl_fonts[i:i + cols] for i in range(0, len(mpl_fonts), cols)]

print("all font list from matplotlib.font_manager:\n")
for row in font_rows:
    print("".join(f"{name:<25}" for name in row))  # 每列宽度 25

运行结果参考

bash 复制代码
all font list from matplotlib.font_manager:

AR PL UKai CN            AR PL UMing CN           Abyssinica SIL           Andale Mono              Ani                      
AnjaliOldLipi            Arial                    Arial Black              C059                     Chandas                  
Chilanka                 Comic Sans MS            Courier New              D050000L                 DejaVu Math TeX Gyre     
DejaVu Sans              DejaVu Sans Display      DejaVu Sans Mono         DejaVu Serif             DejaVu Serif Display     
Dhurjati                 Droid Sans Fallback      Dyuthi                   FreeMono                 FreeSans                 
FreeSerif                Gargi                    Garuda                   Gayathri                 Georgia                  
Gidugu                   Gubbi                    Gurajada                 Impact                   Jamrul                   
KacstArt                 KacstBook                KacstDecorative          KacstDigital             KacstFarsi               
KacstLetter              KacstNaskh               KacstOffice              KacstOne                 KacstPen                 
KacstPoster              KacstQurn                KacstScreen              KacstTitle               KacstTitleL              
Kalapi                   Kalimati                 Karumbi                  Keraleeyam               Khmer OS                 
Khmer OS System          Kinnari                  LKLUG                    LakkiReddy               Laksaman                 
Liberation Mono          Liberation Sans          Liberation Sans Narrow   Liberation Serif         Likhan                   
Lohit Assamese           Lohit Bengali            Lohit Devanagari         Lohit Gujarati           Lohit Gurmukhi           
Lohit Kannada            Lohit Malayalam          Lohit Odia               Lohit Tamil              Lohit Tamil Classical    
Lohit Telugu             Loma                     Mallanna                 Mandali                  Manjari                  
Meera                    Mitra                    Mukti                    NATS                     NTR                      
Nakula                   Navilu                   Nimbus Mono PS           Nimbus Roman             Nimbus Sans              
Nimbus Sans Narrow       Norasi                   Noto Mono                Noto Sans CJK JP         Noto Sans Mono           
Noto Serif CJK JP        OpenSymbol               P052                     Padauk                   Padauk Book              
Pagul                    Peddana                  Phetsarath OT            Ponnala                  Pothana2000              
Potti Sreeramulu         Purisa                   Rachana                  RaghuMalayalamSans       Ramabhadra               
Ramaraja                 Rasa                     RaviPrakash              Rekha                    STIXGeneral              
STIXNonUnicode           STIXSizeFiveSym          STIXSizeFourSym          STIXSizeOneSym           STIXSizeThreeSym         
STIXSizeTwoSym           Saab                     Sahadeva                 Samanata                 Samyak Devanagari        
Samyak Gujarati          Samyak Malayalam         Samyak Tamil             Sarai                    Sawasdee                 
SimHei                   SimSun-ExtB              Sree Krushnadevaraya     Standard Symbols PS      Suranna                  
Suravaram                Suruma                   Syamala Ramana           TenaliRamakrishna        Tibetan Machine Uni      
Times New Roman          Timmana                  Tlwg Mono                Tlwg Typewriter          Tlwg Typist              
Tlwg Typo                Trebuchet MS             URW Bookman              URW Gothic               Ubuntu                   
Ubuntu Condensed         Ubuntu Mono              Umpush                   Uroob                    Vemana2000               
Verdana                  Waree                    Webdings                 WenQuanYi Micro Hei      Yrsa                     
Z003                     aakar                    cmb10                    cmex10                   cmmi10                   
cmr10                    cmss10                   cmsy10                   cmtt10                   dsrom10                  
esint10                  eufm10                   mry_KacstQurn            msam10                   msbm10                   
ori1Uni                  padmaa                   padmaa-Bold.1.1          rsfs10                   stmary10                 
wasy10

ps: SimHei 即是中文黑体,我这里面已经安装了,如果没有安装见步骤(二)

二、将SimHei字体拷贝到matplotlib字体路径下

simhei.tff文件可以在Windows中获取,路径如下

bash 复制代码
C:\Windows\Fonts

查看matplotlib配置文件路径

python 复制代码
import matplotlib as mpl
print(mpl.matplotlib_fname())

输出如下

bash 复制代码
/home/ryan/.local/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc

将上面拷贝的simhei.tff文件放到下面文件夹中

bash 复制代码
/home/ryan/.local/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf

然后再执行一下上面查看支持字体的代码,看看字体是否添加成功。

三、重建字体缓存

删除matplotlib配置文件,将下面路径下的.json文件删除。

bash 复制代码
~/.cache/matplotlib

然后执行

python 复制代码
import matplotlib

#重建历史缓存  更新完字体执行一次就可以
matplotlib.font_manager._load_fontmanager(try_read_cache=False)

测试以下中文能否显示

python 复制代码
import matplotlib.pyplot as plt
import matplotlib as mpl

plt.rcParams['font.sans-serif'] = ['SimHei'] #添加"SimHei"(宋体)到字库族列表中
mpl.rcParams['axes.unicode_minus'] = False #解决负号'-'显示为方块的问题

# 第一个 Figure
fig1, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title("第一张图")

plt.show()  # 显示所有图
相关推荐
REDcker33 分钟前
Linux信号机制详解 POSIX语义与内核要点 sigaction与备用栈实践
linux·运维·php
cui_ruicheng1 小时前
Linux进程间通信(三):System V IPC与共享内存
linux·运维·服务器
蚰蜒螟2 小时前
深入 Linux 内核同步机制:从 futex 到 spinlock 的完整旅程
linux·windows·microsoft
运维全栈笔记2 小时前
Linux安装配置Tomcat保姆级教程:从部署到性能调优
linux·服务器·中间件·tomcat·apache·web
dllmayday3 小时前
Linux 上用终端连接 WiFi
linux·服务器·windows
峥无4 小时前
Linux系统编程基石:静态库·动态库·ELF文件·进程地址空间全景图
linux·运维·服务器
用户2367829801684 小时前
从 chmod 755 说起:Unix 文件权限到底是怎么算的?
linux
Strugglingler4 小时前
【systemctl 学习总结】
linux·systemd·systemctl·journalctl·unit file
全球通史5 小时前
RDKS100 GPU量化环境配置
ubuntu
嵌入式×边缘AI:打怪升级日志6 小时前
100ASK-T113 Pro 开发板 Bootloader 完全开发指南
linux·ubuntu·bootloader