Python中如何统一macOS和Linux下matplotlib的字体配置
我经常在两个平台切换,发现用 python 的 matplotlib 画图时,同样的代码生产的图片中字体不同大小也不同导致排版失真。用
import matplotlib
matplotlib.rcParams
查看关于 font 的配置在两个平台下是一致的,区别大概是有些字体在某个平台下没装吧。
请问有什么办法可以快速方便的统一两平台下的字体设置?比如有没有办法查询 macOS 下默认用了哪些字体?是不是安装上那些字体后 Linux 下就会默认用同样的字体了?谢谢!
Python中如何统一macOS和Linux下matplotlib的字体配置
1、不同系统用统一的字体(自己在每个系统上安装好)。免费的字体既全面(数学、希腊、Cyrillic )且好看的不多,为了排好看的字体,几百美元免不了。
2、手动配置 rcparams,包括数学字体( mathtext ),设置好字号。
3、 手动设置好 figure 的尺寸和 dpi。
( 4、我一般做成 svg,从 inkscape 里重新修改边界,做最后的调整,导出成别的格式。)
图片完全可移植。插到文档里 kerning、ligature、大小、 行间距之类的都与文档很和谐。
在macOS和Linux下统一matplotlib字体配置,关键在于明确指定字体路径和名称。Linux通常使用/usr/share/fonts/,macOS则是/Library/Fonts/或~/Library/Fonts/。
import matplotlib
import matplotlib.pyplot as plt
import platform
import os
def setup_unified_font():
"""统一设置macOS和Linux的matplotlib字体"""
# 获取系统类型
system = platform.system()
if system == 'Darwin': # macOS
# 推荐使用系统自带字体,如Arial、Helvetica
font_path = '/System/Library/Fonts/'
font_name = 'Arial'
# 或者使用用户安装的字体
# font_path = os.path.expanduser('~/Library/Fonts/')
# font_name = 'YourCustomFont'
elif system == 'Linux':
# 常见Linux字体路径
possible_paths = [
'/usr/share/fonts/',
'/usr/local/share/fonts/',
os.path.expanduser('~/.fonts/')
]
# 查找存在的字体目录
font_path = None
for path in possible_paths:
if os.path.exists(path):
font_path = path
break
# Linux常用字体
font_name = 'DejaVu Sans' # 大多数Linux发行版都有
if not font_path:
print("警告: 未找到字体目录,使用matplotlib默认设置")
return
else:
print(f"不支持的系统: {system}")
return
# 配置matplotlib
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = [font_name]
# 如果需要添加自定义字体路径
if font_path and os.path.exists(font_path):
matplotlib.font_manager.fontManager.addfont(font_path)
print(f"已配置字体: {font_name} (系统: {system})")
# 使用示例
if __name__ == "__main__":
setup_unified_font()
# 测试绘图
plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('统一字体测试 - 标题')
plt.xlabel('X轴标签')
plt.ylabel('Y轴标签')
plt.text(2, 2.5, '测试文本', fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
关键点:
- 用
platform.system()检测系统 - macOS常用
Arial或Helvetica - Linux常用
DejaVu Sans或Liberation Sans - 通过
matplotlib.rcParams全局设置
如果要在团队中统一,建议将字体文件放在项目目录的fonts/文件夹中,然后使用相对路径加载,这样完全不受系统影响。
总结:检测系统并分别配置字体路径即可。
考虑一下全面使用 LaTeX 渲染所有文本 。
https://matplotlib.org/users/usetex.html
然后你的问题就变成了,两个操作系统各装一遍 LaTeX。
装了 LaTeX 可以用 pdfcrop 裁 pdf 白边。当然 png 可以用 imagemagick 裁白边。
谢谢!我对 macOS 下默认的效果还是满意的,并不想在 Linux 下手动去全部配置一遍,但现在就是不清楚 macOS 下默认用了什么字体,有办法查询么? rcParams 里面都是给一个列表,如果我的理解没错的话,排在前面的字体优先选择,没装的话就用下一个。
谢谢!是个好办法
要注意像 sans, serif, monospace 这种字体是操作系统 dependent 的。
Good point!
谢谢!原来是那样查询字体的

