diff --git a/src/svgutils/compose.py b/src/svgutils/compose.py index 44ea427..5b64309 100644 --- a/src/svgutils/compose.py +++ b/src/svgutils/compose.py @@ -105,9 +105,26 @@ class SVG(Element): full path to the file """ - def __init__(self, fname): - fname = os.path.join(CONFIG['svg.file_path'], fname) - svg = _transform.fromfile(fname) + def __init__(self, fname=None): + if fname: + fname = os.path.join(CONFIG['svg.file_path'], fname) + svg = _transform.fromfile(fname) + self.root = svg.getroot().root + + +class MplFigure(SVG): + """Matplotlib figure + + Parameters + ---------- + fig : matplotlib Figure isinstanc + instance of Figure to be converted + kws : + keyword arguments passed to matplotlib's savefig method + """ + + def __init__(self, fig, **kws): + svg = _transform.from_mpl(fig, savefig_kw=kws) self.root = svg.getroot().root diff --git a/src/svgutils/transform.py b/src/svgutils/transform.py index 2a4b387..288972c 100644 --- a/src/svgutils/transform.py +++ b/src/svgutils/transform.py @@ -336,7 +336,7 @@ def fromstring(text): return fig -def from_mpl(fig, savefig_kw): +def from_mpl(fig, savefig_kw=None): """Create a SVG figure from a ``matplotlib`` figure. Parameters @@ -346,7 +346,7 @@ def from_mpl(fig, savefig_kw): savefig_kw : dict keyword arguments to be passed to matplotlib's `savefig` - + Returns @@ -366,7 +366,7 @@ def from_mpl(fig, savefig_kw): >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> line, = plt.plot([1,2]) - >>> svgfig = transform.from_mpl(fig, + >>> svgfig = transform.from_mpl(fig, ... savefig_kw=dict(transparent=True)) >>> svgfig.getroot() @@ -375,9 +375,11 @@ def from_mpl(fig, savefig_kw): """ fid = StringIO() + if savefig_kw is None: + savefig_kw = {} try: - fig.savefig(fid, format='svg') + fig.savefig(fid, format='svg', **savefig_kw) except ValueError: raise(ValueError, "No matplotlib SVG backend") fid.seek(0)