在 WSL2 的 Ubuntu 中安装中文字体

在 WSL2 的 Ubuntu 中安装中文字体,以支持 matplotlib 等工具的中文显示,主要有两种方法:通过包管理器安装开源字体和从 Windows 主机导入字体。

您代码中指定的 WenQuanYi Micro Hei(文泉驿微米黑)是一个很好的选择,可以通过 apt 直接安装。

方法一:通过 apt 安装中文字体包(推荐)

这是最简单、最直接的方法。

  1. 更新软件包列表:

    sudo apt update

  2. 安装"文泉驿微米黑"字体:

    sudo apt install fonts-wqy-microhei

  3. (可选)安装其他常用开源中文字体,以获得更多选择:

    文泉驿正黑

    sudo apt install fonts-wqy-zenhei

    思源字体家族(Adobe/Google 合作的开源字体,质量很高)

    sudo apt install fonts-noto-cjk

  4. 清除并重建 matplotlib 的字体缓存:

    安装新字体后,matplotlib 可能不会立即识别,需要强制重建其缓存。

    rm -rf ~/.cache/matplotlib

    下次运行 Python 脚本时,matplotlib 会自动生成新缓存。

方法二:从 Windows 主机复制字体(使用已有字体)

如果你希望在 Linux 中使用 Windows 系统里已有的字体(如微软雅黑、SimHei 等),可以按以下步骤操作。

  1. 在 WSL 中创建字体目录:

    mkdir -p ~/.local/share/fonts

  2. 从 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/ # 宋体

  3. 刷新系统字体缓存:

    fc-cache -fv

  4. 同样,清除 matplotlib 缓存:

    rm -rf ~/.cache/matplotlib

验证安装

  1. 检查字体是否被系统识别:

    fc-list :lang=zh

    这个命令会列出所有已安装的中文字体。查看输出中是否包含你安装的字体名,如 WenQuanYi Micro Hei, Noto Sans CJK SC, Microsoft YaHei 等。

  2. 在 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 缓存后,可能需要重启内核才能让新设置生效。

相关推荐
洛菡夕2 小时前
LNMP环境部署
linux·运维
Rsun045512 小时前
Docker部署项目
运维·docker·容器
jnrjian2 小时前
Offending ECDSA key in /home/oracle/.ssh/known_hosts:16
运维·ssh
yqzyy2 小时前
如何安装配置Goland并使用固定公网地址SSH远程连接本地服务器
运维·服务器·ssh
AMoon丶2 小时前
C++新特性-智能指针
linux·服务器·c语言·开发语言·c++·后端·tcp/ip
蜕变的小白2 小时前
Linux系统编程-->高效并发服务器:IO多路复用详解
linux·运维·服务器
Johnstons2 小时前
AnaTraf 网络流量分析免费版:给运维多一双“眼睛”
运维·服务器·网络
峥嵘life2 小时前
Android16 EDLA更新25-12补丁导致【CTS】CtsWindowManagerDeviceAnimations存在fail项
android·linux·学习
草莓熊Lotso2 小时前
手搓简易 Linux 进程池:从 0 到 1 实现基于管道的任务分发系统
linux·运维·服务器·数据库·c++·人工智能