matplotlib画图时,每句文本只使用一种字体进行显示。Times New Roman英文字体和宋体为常用字体,为同时显示这两种字体,翻阅了很多文章,终于找到一种完美的解决方案。即:合并中英文字体。
一、合并步骤描述
- 首先,下载并解压合并工具(工具链接: GitHub - nowar-fonts/Warcraft-Font-Merger: Warcraft Font Merger,魔兽世界字体合并/补全工具。)。
- 其次,根据Github页面提示,合并新罗马字体(times.ttf)与宋体(simsun.ttc),两种字体在Win10系统下的文件夹位置为:"C:/Windows/Fonts"。合并后的字体文件路径可查看Github说明,默认为"out.ttf"。
为方便读者,给出合并这两种特定字体的批处理脚本(简化查找字体并拖动文件的步骤)。直接运行即可
- 先在合并工具文件夹内,使用新建记事本文件然后改后缀名的方式,新建一个"a.bat"文件,注意后缀名是bat,不是txt!否则无法通过双击运行该文件。
- 右键编辑bat文件,将以下内容复制到bat文件里,并保存该文件
%~d0
cd "%~dp0"
.\otfccdump.exe --ignore-hints -o base.otd "C:\Windows\fonts\times.ttf"
.\otfccdump.exe --ignore-hints -o ext.otd "C:\Windows\fonts\simsun.ttc"
.\merge-otd.exe base.otd ext.otd
.\otfccbuild.exe -q -O3 -o tnw+simsun.ttf base.otd
del base.otd ext.otd
pause
- 双击运行"a.bat"文件,合并后的文件在文件夹内,名称为"tnw+simsun.ttf"
注:以上工具提供和合并后字体的蓝秦云链接。合并工具、合并字体
二、效果查看
通过编写Python代码检查合并效果:
from matplotlib import font_manager
from matplotlib import rcParams
import os
# 字体加载
font_path = "Your font file's path."
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)
# print(prop.get_name()) # 显示当前使用字体的名称
# 字体设置
rcParams['font.family'] = 'sans-serif' # 使用字体中的无衬线体
rcParams['font.sans-serif'] = prop.get_name() # 根据名称设置字体
rcParams['font.size'] = 10 # 设置字体大小
rcParams['axes.unicode_minus'] = False # 使坐标轴刻度标签正常显示正负号
# 图片显示
if __name__ == '__main__':
import matplotlib.pyplot as plt
plt.title("宋体Times New Roman")
plt.show()
参考阅读:知乎