如何将matplotlib图的输出作为SVG?

问题描述 投票:43回答:2

我需要获取matplotlib图的输出并将其转换为我可以在激光切割机上使用的SVG路径。

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,100,0.00001)
y = x*np.sin(2*pi*x)
plt.plot(y)
plt.show()

例如,下面您会看到一个波形。我希望能够将此波形输出或保存为SVG路径,以后我可以在Adobe Illustrator等程序中使用该路径。

我知道matplotlib可以使用的一个名为“Cairo”的SVG库(matplotlib.use('Cairo')),但是我不清楚这会让我访问我需要的SVG路径,即使matplotlib现在将使用Cairo来生成情节。

我确实有cairo在我的系统上工作,并且可以成功绘制一个由SVG路径组成的示例,我确实可以在Illustrator中编辑它,但是我没有办法将上面的等式转换为SVG路径。

import cairo
from cairo import SVGSurface, Context, Matrix    
s = SVGSurface('example1.svg', WIDTH, HEIGHT)
c = Context(s)

# Transform to normal cartesian coordinate system
m = Matrix(yy=-1, y0=HEIGHT)
c.transform(m)

# Set a background color
c.save()
c.set_source_rgb(0.3, 0.3, 1.0)
c.paint()
c.restore()

# Draw some lines
c.move_to(0, 0)
c.line_to(2 * 72, 2* 72)
c.line_to(3 * 72, 1 * 72)
c.line_to(4 * 72, 2 * 72)
c.line_to(6 * 72, 0)
c.close_path()
c.save()
c.set_line_width(6.0)
c.stroke_preserve()
c.set_source_rgb(0.3, 0.3, 0.3)
c.fill()
c.restore()

# Draw a circle
c.save()
c.set_line_width(6.0)
c.arc(1 * 72, 3 * 72, 0.5 * 72, 0, 2 * pi)
c.stroke_preserve()
c.set_source_rgb(1.0, 1.0, 0)
c.fill()
c.restore()

# Save as a SVG and PNG
s.write_to_png('example1.png')
s.finish()

(请注意,此处显示的图像为png,因为stackoverflow不接受显示的svg图形)

python svg matplotlib interpolation cairo
2个回答
51
投票

您很可能想要修复图像大小并摆脱各种背景和轴标记:

import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = x*np.sin(2* np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
plt.savefig("test.svg")

生成的SVG文件只包含一个额外的元素,因为savefig确实想要保存图形背景。这种背景的颜色很容易变为'无',但它似乎没有摆脱它。无论如何,SVG非常干净,而且尺寸正确(每单位1/72“)。


22
投票

根据您使用的后端(我在TkAgg和Agg上测试),它应该像在savefig()调用中指定它一样简单:

import matplotlib.pyplot as plt                                                                                                                                                               
import numpy as np
x = np.arange(0,100,0.00001)
y = x*np.sin(2*np.pi*x)
plt.plot(y)
plt.savefig("test.svg", format="svg")
© www.soinside.com 2019 - 2024. All rights reserved.