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

时间:2014-12-26 12:39:52

标签: python svg matplotlib inkscape

我有一些用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中调整所有内容更好的方法:)

1 个答案:

答案 0 :(得分:2)

这是Inkscape的问题:始终测量字体大小(以像素为单位)(而非点数)。字体大小因子1.25来自于inkscape使用90像素/英寸这一事实,并且您在matplotlib中指定的字体大小为72磅/英寸。

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

但是,如果将svg保存到inkscape中的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")

enter image description here