如何让Matplotlib识别并使用非TTF格式的Helvetica或替代字体?
解决方案
1. 转换PCF字体为TTF格式
Matplotlib不支持PCF格式,通过fontforge工具将其转换为TTF即可:
- 安装转换工具:
sudo dnf install fontforge - 解压PCF压缩包:
gunzip /usr/share/X11/fonts/75dpi/helvR24-ISO8859-1.pcf.gz - 执行格式转换(以常规Helvetica为例):
fontforge -lang=ff -c 'Open($1); Generate($2)' helvR24-ISO8859-1.pcf helvetica-regular.ttf - 部署转换后的字体并更新缓存:
sudo mkdir -p /usr/share/fonts/custom sudo mv helvetica-regular.ttf /usr/share/fonts/custom/ sudo fc-cache -fv rm -rf ~/.cache/matplotlib/ - 验证:进入Python终端执行
import matplotlib.font_manager print([f.name for f in matplotlib.font_manager.fontManager.ttflist if 'Helvetica' in f.name])
2. 正确安装Tex Gyre Heros的TTF/OTF字体
当前安装的texlive-tex-gyre仅包含文档,需安装字体文件包:
- 安装带字体文件的包:
sudo dnf install texlive-tex-gyre-fonts - 查找OTF字体位置(Matplotlib 3.0.3已支持OTF):
find /usr/share/texlive/ -name "texgyreheros*.otf" - 将字体复制到系统字体目录(若未自动识别):
sudo cp /usr/share/texlive/texmf-dist/fonts/opentype/public/tex-gyre/*.otf /usr/share/fonts/custom/ sudo fc-cache -fv rm -rf ~/.cache/matplotlib/ - 在Matplotlib中配置使用该字体:
修改Matplotlib配置文件(路径可通过matplotlib.get_configdir()获取)中的matplotlibrc:font.family: sans-serif sans-serif: Tex Gyre Heros, DejaVu Sans
3. 利用Fontconfig间接映射(兼容性有限)
对于旧版本Matplotlib,可尝试通过Fontconfig将PCF字体映射为Matplotlib可识别的名称,但成功率不高:
- 确保Matplotlib使用支持Fontconfig的后端(如
TkAgg),修改matplotlibrc:backend: TkAgg - 配置Fontconfig将Helvetica映射到系统已有的TTF字体,或让Matplotlib优先使用Fontconfig的字体查找逻辑,但此方法对3.0.3版本的兼容性不稳定。
内容的提问来源于stack exchange,提问作者irritable_phd_syndrome
相关产品推荐
相关产品推荐

