在Matplotlib中使用开放式字体和pdf exp的字体缩放

2024-05-13 15:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是对matplotlib图形中的所有文本(常规和数学)使用特定字体,例如Nimbus Sans L或Tex Gyre Heros。这两种字体以.otf文件的形式提供。当我运行下面的代码时,png图像是正确生成的,但是在pdf中标题和轴号的字母之间有额外的空格。从默认的10pt更改字体大小似乎会产生奇怪的缩放比例。在

有问题的pdf:

enter image description here

png好的:

enter image description here

我所做的: 它似乎可以很好地与.ttf字体一起工作。在

我使用的是:matplotlib 2.0.0,python3.5.2

示例代码:

import matplotlib as mpl

import numpy as np
x = np.linspace(-3, 10, 100)
ymodel = x**2
ydata = ymodel + 20 * (np.random.rand(len(x)) - 0.5)

font = 'tex gyre heros'  # an open type font

mpl.rcParams['font.sans-serif'] = font
mpl.rc('mathtext', fontset='custom', it=font + ':italic')
mpl.rc('font', size=13)  # change font size from default 10

import matplotlib.pyplot as plt
plt.figure()    
plt.plot(x, ydata, 'o')
plt.plot(x, ymodel)
plt.xlabel("Something for the $x$ axis (units)")
plt.ylabel("The $y$ axis (units)")
plt.title("{}".format(font.upper()))
plt.text(0, 80, "Some math: $\chi_{13}=-3\pi\psi\Delta_A\\times\omega + x^2$")

plt.savefig("fig_" + font.lower() + ".pdf", bbox_inches='tight')
plt.savefig("fig_" + font.lower() + ".png", bbox_inches='tight', dpi=300)

Tags: 代码importsizepdfpngmatplotlibasnp