我需要获取 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 图形进行显示)