一般我们在用matplotlib画图时,为了正常显示中文,会用如下代码
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["axes.unicode_minus"]=False
但Linux系统中默认没有安装中文字体,需要手动下载字体文件,但如果是在Windows Linux子系统(wsl2)上可以有更简单的处理办法,参考文章WSL2 安装中文字体,运行以下命令
sudo ln -s /mnt/c/Windows/Fonts /usr/share/fonts/font
通过使用Windows自带字体的方式,来实现快速安装中文字体。接下来运行
fc-cache -fv
刷新字体缓存。这里如果报错,安装fontconfig即可
sudo apt update
sudo apt install fontconfig
接下来打开python,输入以下命令,打印matplotlib原来的字体缓存路径
import matplotlib as mpl
print(mpl.get_cachedir())
用rm -r删除这个路径。
重启jupyter内核,此时matplotlib会刷新字体缓存
完成之后就可以正常用中文绘图。