How can I get the output of a matplotlib plot as an SVG?

You will most probably want to fix the image size and get rid of all sorts of backgrounds and axis markers:

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

The resulting SVG file contains only one extra element, as savefig really wants to save the figure background. The color of this background is easy to change to ‘none’, but it does not seem to get rid of it. Anyway, the SVG is very clean otherwise and in the correct scale (1/72″ per unit).

Leave a Comment