在linux中使用matplotlib(包括sns)绘图保存后,下载到window里Adobe AI打开时,遇到了这样的报错。如下探索的解决方法记录。

  • 问题1:将文本识别为路径
image-20260331094732752
  • 问题2:无法设置Arial字体
image-20260331100326525
  • 问题1的解决方法
1
2
import matplotlib as mpl
mpl.rcParams["pdf.fonttype"] = 42           # 使得AI打开是文本而不是路径
  • 问题2的解决方法
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## (1) 首先确认系统有没有安装Arial字体

from matplotlib import font_manager as fm
[f.name for f in fm.fontManager.ttflist if "Arial" in f.name]
# []
print(fm.findfont("Arial"))


## (2) 如果没有,去网上下载一个
# https://github.com/matomo-org/travis-scripts/blob/master/fonts/Arial.ttf
ls ~/.fonts/arial/
# Arial.ttf

## (3) 更新字体配置
fc-cache -fv
rm -rf ~/.cache/matplotlib  # Matplotlib 有字体缓存
  • 完整记录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import seaborn as sns

# 如何需要设置sns的主题, 一定要放在mpl的上面; 否则会覆盖下面的设置
sns.set_theme(style="whitegrid")   

import matplotlib as mpl
mpl.rcParams["pdf.fonttype"] = 42           # AI打开是文本而不是路径
mpl.rcParams["font.sans-serif"] = ["Arial"] # Arial字体
mpl.rcParams["axes.unicode_minus"] = False  # 负号的显示


fig, ax = plt.subplots(figsize=(8, 5))
sns.barplot(x=["A", "B", "C"], y=[10, 15, 8], ax=ax)

ax.set_title(" Test Title")
ax.set_xlabel("xlabel")
ax.set_ylabel("ylabel")

plt.tight_layout()
plt.savefig("./test.pdf")