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

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 pltimport numpy as npplt.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).


Depending on the backend you use (I tested on TkAgg and Agg) it should be as easy as specifying it within the savefig() call:

import matplotlib.pyplot as plt                                                                                                                                                               import numpy as npx = np.arange(0,100,0.00001)y = x*np.sin(2*np.pi*x)plt.plot(y)plt.savefig("test.svg", format="svg")