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

标签 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 中调整所有内容的大小更好的方法:)

最佳答案

这是 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")

enter image description here

关于python - 从 matplotlib 保存 svg 时更改字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657285/

相关文章:

python - 用于分配数组元素的 Numpy 语法

javascript - 单击 D3.js 隐藏可见元素

python - 选择列与上一行不同的行

python - 使用正则表达式在 Python 中获取两个字符串之间的 channel

python - 在Windows cmd中以颜色显示用户输入的文本

javascript - 如何更改innerHTML的innerHTML

svg - GraphViz - 将边缘标签链接到另一个点图

python - 使用 Python 的 matplotlib 选择要在屏幕上显示哪些图形以及将哪些图形保存到文件中

fonts - python matplotlib mathtext AMSeuler 字体

pandas - 如何修复属性错误: 'Series' object has no attribute 'find' ?