Skip to main content
 首页 » 编程设计

python之从 matplotlib 保存 svg 时更改字体大小

2024年10月25日9del

我有一些数据可以用 matplotlib 可视化。我使用的字体是 Arial,字体大小应该是 10。我将图表保存为 svg,以便在 inkscape 中对其进行后期处理。一切都很顺利,直到轴刻度、标签等的字体大小为 12,5 而不是 10。下面是我定义 rcParams 的代码:

mpl.rcParams['axes.labelsize'] = 10 
mpl.rcParams['xtick.labelsize'] = 10 
mpl.rcParams['ytick.labelsize'] = 10 
mpl.rcParams['legend.fontsize'] = 10 
 
mpl.rcParams['font.family'] = ['sans-serif'] 
mpl.rcParams['font.sans-serif'] = ['Arial'] 
mpl.rcParams['text.usetex'] = False 
 
mpl.rcParams['svg.fonttype'] = 'none' 
 
do some stuff: fig, plt.plot, etc. 
 
fig.savefig('fig.svg',dpi=300, bbox_inches='tight',transparent=True) 

肯定有比在 inkscape 中调整所有内容更好的方法:)

请您参考如下方法:

这是 Inkscape 的问题:它总是以像素(而不是磅)为单位测量字体大小。字体大小的因子 1.25 是由于 inkscape 使用 90 像素/英寸而您在 matplotlib 中指定的字体大小假设为 72 点/英寸。

进一步阅读:http://www.inkscapeforum.com/viewtopic.php?f=6&t=5964

但是,如果您在 inkscape 中将 svg 保存为 pdf(在后处理之后),您将获得与以下示例所示相同的字体大小:

import matplotlib as mpl 
import matplotlib.pyplot as plt 
import os 
 
mpl.rcParams['axes.labelsize'] = 10 
mpl.rcParams['xtick.labelsize'] = 10 
mpl.rcParams['ytick.labelsize'] = 10 
mpl.rcParams['legend.fontsize'] = 10 
mpl.rcParams['font.family'] = ['sans-serif'] 
mpl.rcParams['font.sans-serif'] = ['Arial'] 
mpl.rcParams['text.usetex'] = False 
mpl.rcParams['svg.fonttype'] = 'none' 
 
 
fig = plt.figure(figsize=(4,1)) 
for pos,ts in enumerate(range(8,16)): 
    plt.text(pos,0.5,ts, fontsize=ts) 
plt.plot([-1,pos+1],[0.5,0.5]) 
plt.gca().yaxis.set_visible(False) 
plt.gca().xaxis.set_visible(False) 
 
# save as svg and pdf 
plt.title('svg') 
fig.savefig('figure.svg',dpi=300, bbox_inches='tight',transparent=True) 
plt.title('pdf') 
fig.savefig('figure.pdf',dpi=300, bbox_inches='tight',transparent=True) 
 
# use inkscape to convert svg to pdf 
os.system("inkscape --export-area-page --export-dpi=300 " \ 
        "--export-pdf=figure2.pdf -f=figure.svg") 
 
# concatenate pdfs for comparison and make png 
os.system("pdfnup --nup 1x2 -o output.pdf figure.pdf figure2.pdf") 
os.system("convert -density 300 output.pdf output.png")