在 WSL2 的 Ubuntu 中安装中文字体,以支持 matplotlib 等工具的中文显示,主要有两种方法:通过包管理器安装开源字体和从 Windows 主机导入字体。
您代码中指定的 WenQuanYi Micro Hei(文泉驿微米黑)是一个很好的选择,可以通过 apt 直接安装。
方法一:通过 apt 安装中文字体包(推荐)
这是最简单、最直接的方法。
-
更新软件包列表:
sudo apt update
-
安装"文泉驿微米黑"字体:
sudo apt install fonts-wqy-microhei
-
(可选)安装其他常用开源中文字体,以获得更多选择:
文泉驿正黑
sudo apt install fonts-wqy-zenhei
思源字体家族(Adobe/Google 合作的开源字体,质量很高)
sudo apt install fonts-noto-cjk
-
清除并重建 matplotlib 的字体缓存:
安装新字体后,matplotlib 可能不会立即识别,需要强制重建其缓存。
rm -rf ~/.cache/matplotlib
下次运行 Python 脚本时,matplotlib 会自动生成新缓存。
方法二:从 Windows 主机复制字体(使用已有字体)
如果你希望在 Linux 中使用 Windows 系统里已有的字体(如微软雅黑、SimHei 等),可以按以下步骤操作。
-
在 WSL 中创建字体目录:
mkdir -p ~/.local/share/fonts
-
从 Windows 复制字体文件。
Windows 字体通常位于 C:\Windows\Fonts。在 WSL 中,该路径对应为 /mnt/c/Windows/Fonts/。
◦ 复制单个字体(例如微软雅黑 msyh.ttc):
cp /mnt/c/Windows/Fonts/msyh.ttc ~/.local/share/fonts/
◦ 复制多个常用中文字体:
cp /mnt/c/Windows/Fonts/simhei.ttf ~/.local/share/fonts/ # 黑体
cp /mnt/c/Windows/Fonts/simkai.ttf ~/.local/share/fonts/ # 楷体
cp /mnt/c/Windows/Fonts/simsun.ttc ~/.local/share/fonts/ # 宋体
-
刷新系统字体缓存:
fc-cache -fv
-
同样,清除 matplotlib 缓存:
rm -rf ~/.cache/matplotlib
验证安装
-
检查字体是否被系统识别:
fc-list :lang=zh
这个命令会列出所有已安装的中文字体。查看输出中是否包含你安装的字体名,如 WenQuanYi Micro Hei, Noto Sans CJK SC, Microsoft YaHei 等。
-
在 Python 中测试:
创建一个测试脚本 test_chinese.py:
import matplotlib.pyplot as plt
import matplotlib
列出所有已发现的中文字体
zh_fonts = [f.name for f in matplotlib.font_manager.fontManager.ttflist if 'hei' in f.name.lower() or 'noto' in f.name.lower() or 'yahei' in f.name.lower()]
print("可用的中文字体样本:", set(zh_fonts[:10])) # 打印前10个看看
import matplotlib.pyplot as plt
import seaborn as sns
1. 先设置Seaborn
sns.set_style("whitegrid")
sns.set_palette("husl")
2. 然后设置中文字体
plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'DejaVu Sans', 'Arial']
plt.rcParams['axes.unicode_minus'] = False
plt.figure()
plt.title('测试中文标题 - 马年大吉')
plt.xlabel('横坐标 X')
plt.ylabel('纵坐标 Y')
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
运行它,看图表标题和坐标轴标签是否能正确显示中文。
总结与建议
• 首选方法一,运行 sudo apt install fonts-wqy-microhei fonts-noto-cjk。这两个开源字体质量高,基本能满足所有需求,且最省事。
• 你的 plt.rcParams 设置将 WenQuanYi Micro Hei 放在最优先位置,安装对应字体后即可生效。
• 如果使用 Jupyter Notebook,在安装字体并清除 matplotlib 缓存后,可能需要重启内核才能让新设置生效。