我需要获取一个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等程序中使用。
我知道一个名为“Cairo”的SVG库,它可以使用matplotlib(matplotlib.use(‘Cairo’)),但是我并不清楚,这将使我能够访问我需要的SVG路径,即使matplotlib将现在正在使用开罗来生成情节。
我确实有开罗工作在我的系统,并可以成功地绘制一个由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图形显示)