在使用matplotlib绘图时, 指定Times New Roman字体:
import matplotlib.font_manager as fm
# 设置字体为"Times New Roman",首先检查字体是否可用
font_path = fm.findfont('Times New Roman')
prop = fm.FontProperties(fname=font_path, weight='bold')
结果报错:
findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans.
我的临时解决方案是, 网上下载Times New Roman.ttf资源:
https://github.com/justrajdeep/fonts/blob/master/Times%20New%20Roman.ttf
进入容器路径, 创建新的文件夹/usr/share/fonts/truetype/myfonts, 复制.ttf资源到该路径.
后续: 在matplotlib注册使用更多字体:
import matplotlib.font_manager as fm
from matplotlib import rcParams
font_paths = {
'regular': '/usr/share/fonts/truetype/myfonts/times.ttf',
'bold': '/usr/share/fonts/truetype/myfonts/timesbd.ttf',
}
font_properties = {
'regular': fm.FontProperties(fname=font_paths['regular']),
'bold': fm.FontProperties(fname=font_paths['bold'], size=22),
'bold0': fm.FontProperties(fname=font_paths['bold'], size=20),
}
# 使用时, 指定font_properties
fig.text(0.45, 0, 'Wavelength (nm)', ha='center', va='center', fontproperties=font_properties['bold'])