Skip to content

Commit

Permalink
added MplFigure class
Browse files Browse the repository at this point in the history
  • Loading branch information
btel committed Jan 26, 2018
1 parent 72e73d0 commit 5381b82
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
23 changes: 20 additions & 3 deletions src/svgutils/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
10 changes: 6 additions & 4 deletions src/svgutils/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -346,7 +346,7 @@ def from_mpl(fig, savefig_kw):
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
Expand All @@ -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()
<svgutils.transform.GroupElement object at ...>
Expand All @@ -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)
Expand Down

0 comments on commit 5381b82

Please sign in to comment.