如何将文本保存在 python 可编辑的 svg 文件中?

How do I save the text in python plots editable in svg files?

我正在尝试将 python 图保存为 svg 文件:

import matplotlib as mpl
mpl.use('svg')
import matplotlib.pyplot as plt
import numpy as np

plt.figure()
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('Phase $\phi$')
plt.ylabel('Signal')
plt.savefig('SineSignal.svg', format = 'svg')

目前有效。 但是一旦我在 Inkscape 中打开文件,我就不能再编辑文本了。似乎 python 将文本保存为图形而不是文本。因此,我既不能在 Inkscape 中更改字体、字体大小等,也不能在我用乳胶创建的 PDF 文件的图中搜索文本元素。

另一种选择是将绘图保存为 PGF(在这种情况下,mpl.use('svg') 必须替换为 mpl.use('pgf'):

plt.savefig('SineSignal.pgf')

这样我仍然无法编辑font/fontsize,但至少我可以在pdf中搜索textelements。

有什么建议吗? 在 python 中使用 TikZ 不是一种选择,因为功能非常有限,而且绘图看起来会有所不同。

从头开始选项

带红色圆圈的 SVG 文件的最少代码;保存到 circle.svg:

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
  <circle id="circle--red" cx="30" cy="30" r="30" fill="#f00"/>
</svg>

您可能需要 <path> 在 SVG 中创建正弦波曲线。 https://www.w3schools.com/graphics/svg_path.asp 替换上面的 <circle> 元素。对于文本,使用 <text>https://www.w3schools.com/graphics/svg_text.asp

如果您想要轴,可以自己生成,但使用 Inkscape 或其他支持 SVG 的图形编辑器可能有助于创建轴原型。

找到答案。您可以使用

new_rc_params = {'text.usetex': False,
"svg.fonttype": 'none'
}
mpl.rcParams.update(new_rc_params)

防止 svg 后端将文本呈现为路径。 有关更详细的说明,请查看 .