[Python-modules-commits] [python-mplexporter] 104/135: Added a `draw_legend` context manager.

Wolfgang Borgert debacle at moszumanska.debian.org
Tue Sep 23 21:19:09 UTC 2014


This is an automated email from the git hooks/post-receive script.

debacle pushed a commit to branch master
in repository python-mplexporter.

commit 5d34a3d93ab6037ad6137b8ea011fc39fbc3dd10
Author: theengineear <andseier at gmail.com>
Date:   Fri Mar 14 18:58:47 2014 -0700

    Added a `draw_legend` context manager.
    
    To ignore commands from the exporter, renderers can check the following
    attribute from the Renderer class from which they are a subclass:
    
    `if self._current_legend is not None`
    
    Files Changed:
    ==============
    
    exporter.py
    -----------
    - added `crawl_legend`, similar to other `crawl_*` methods
    - within `crawl_ax`, renderer's `draw_legend` is now called
    
    base.py
    -------
    - added `draw_legend`, a context manager
    - added `open_legend`, to be reimplemented by subclasses
    - added `close_legend`, to be reimplemented by subclasses
    
    utils.py
    --------
    - added `get_legend_properties`, just returns handles and labels
    
    fake_renderer.py
    ----------------
    - updated self.output to include opening and closing legends
    
    test_basic.py
    -------------
    - updated comparison strings to include opening and closing legends
---
 mplexporter/exporter.py                | 39 +++++++++++++++++++---------------
 mplexporter/renderers/base.py          | 32 ++++++++++++++++++++++++++++
 mplexporter/renderers/fake_renderer.py |  6 ++++++
 mplexporter/tests/test_basic.py        | 22 +++++++++++++++++++
 mplexporter/utils.py                   |  6 +++++-
 5 files changed, 87 insertions(+), 18 deletions(-)

diff --git a/mplexporter/exporter.py b/mplexporter/exporter.py
index 2c9c9a0..509e714 100644
--- a/mplexporter/exporter.py
+++ b/mplexporter/exporter.py
@@ -140,23 +140,28 @@ class Exporter(object):
                 self.draw_image(ax, image)
 
             legend = ax.get_legend()
-            if legend is not None:
-                for child in ax.legend_.get_children():
-                    # force a large zorder so it appears on top
-                    child.set_zorder(1E6 + child.get_zorder())
-                    if isinstance(child, matplotlib.patches.Patch):
-                        self.draw_patch(ax, child, force_trans=ax.transAxes)
-                    elif isinstance(child, matplotlib.text.Text):
-                        if not (child is ax.legend_.get_children()[-1]
-                                and child.get_text() == 'None'):
-                            self.draw_text(ax, child, force_trans=ax.transAxes)
-                    elif isinstance(child, matplotlib.lines.Line2D):
-                        self.draw_line(ax, child, force_trans=ax.transAxes)
-                    elif isinstance(child, matplotlib.offsetbox.PackerBase):
-                        pass
-                    else:
-                        warnings.warn("Legend element %s not impemented"
-                                      & child)
+            with self.renderer.draw_legend(
+                    legend=legend,
+                    props=utils.get_legend_properties(ax)):
+                if legend is not None:
+                    self.crawl_legend(ax, legend)
+
+    def crawl_legend(self, ax, legend):
+        for child in legend.get_children():
+            # force a large zorder so it appears on top
+            child.set_zorder(1E6 + child.get_zorder())
+            if isinstance(child, matplotlib.patches.Patch):
+                self.draw_patch(ax, child, force_trans=ax.transAxes)
+            elif isinstance(child, matplotlib.text.Text):
+                if not (child is legend.get_children()[-1]
+                        and child.get_text() == 'None'):
+                    self.draw_text(ax, child, force_trans=ax.transAxes)
+            elif isinstance(child, matplotlib.lines.Line2D):
+                self.draw_line(ax, child, force_trans=ax.transAxes)
+            elif isinstance(child, matplotlib.offsetbox.PackerBase):
+                pass
+            else:
+                warnings.warn("Legend element %s not impemented" & child)
 
     def draw_line(self, ax, line, force_trans=None):
         """Process a matplotlib line and call renderer.draw_line"""
diff --git a/mplexporter/renderers/base.py b/mplexporter/renderers/base.py
index 13d9855..11ff029 100644
--- a/mplexporter/renderers/base.py
+++ b/mplexporter/renderers/base.py
@@ -57,6 +57,16 @@ class Renderer(object):
         self._current_ax = None
         self._ax_props = {}
 
+    @contextmanager
+    def draw_legend(self, legend, props):
+        self._current_legend = legend
+        self._legend_props = props
+        self.open_legend(legend=legend, props=props)
+        yield
+        self.close_legend(legend=legend)
+        self._current_legend = None
+        self._legend_props = {}
+
     # Following are the functions which should be overloaded in subclasses
 
     def open_figure(self, fig, props):
@@ -107,6 +117,28 @@ class Renderer(object):
         """
         pass
 
+    def open_legend(self, legend, props):
+        """
+        Beging commands for a particular legend.
+
+        Parameters
+        ----------
+        legend : matplotlib.legend.Legend
+                The Legend that will contain the ensuing elements
+        props : dictionary
+                The dictionary of legend properties
+        """
+
+    def close_legend(self, legend):
+        """
+        Finish commands for a particular legend.
+
+        Parameters
+        ----------
+        legend : matplotlib.legend.Legend
+                The Legend which is finished being drawn
+        """
+
     def draw_marked_line(self, data, coordinates, linestyle, markerstyle,
                          label, mplobj=None):
         """Draw a line that also has markers.
diff --git a/mplexporter/renderers/fake_renderer.py b/mplexporter/renderers/fake_renderer.py
index a50a3b1..2c4c708 100644
--- a/mplexporter/renderers/fake_renderer.py
+++ b/mplexporter/renderers/fake_renderer.py
@@ -29,6 +29,12 @@ class FakeRenderer(Renderer):
     def close_axes(self, ax):
         self.output += "  closing axes\n"
 
+    def open_legend(self, legend, props):
+        self.output += "    opening legend\n"
+
+    def close_legend(self, legend):
+        self.output += "    closing legend\n"
+
     def draw_text(self, text, position, coordinates, style,
                   text_type=None, mplobj=None):
         self.output += "    draw text '{0}' {1}\n".format(text, text_type)
diff --git a/mplexporter/tests/test_basic.py b/mplexporter/tests/test_basic.py
index 82f98eb..d36844f 100644
--- a/mplexporter/tests/test_basic.py
+++ b/mplexporter/tests/test_basic.py
@@ -30,6 +30,8 @@ def test_lines():
                          opening figure
                          opening axes
                          draw path with 20 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -39,6 +41,8 @@ def test_lines():
                          opening figure
                          opening axes
                          draw line with 20 points
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -54,6 +58,8 @@ def test_markers():
                          opening axes
                          draw path with 25 vertices
                          draw path with 25 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -63,6 +69,8 @@ def test_markers():
                          opening figure
                          opening axes
                          draw 2 markers
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -79,6 +87,8 @@ def test_path_collection():
                          draw path with 25 vertices
                          draw path with 25 vertices
                          draw path with 25 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -88,6 +98,8 @@ def test_path_collection():
                          opening figure
                          opening axes
                          draw path collection with 3 offsets
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -108,6 +120,8 @@ def test_text():
                          draw text 'my x label' xlabel
                          draw text 'my y label' ylabel
                          draw text 'my title' title
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -124,6 +138,8 @@ def test_path():
                          opening axes
                          draw path with 25 vertices
                          draw path with 4 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -139,9 +155,13 @@ def test_multiaxes():
                          opening figure
                          opening axes
                          draw path with 4 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          opening axes
                          draw path with 10 vertices
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
@@ -158,6 +178,8 @@ def test_image():
                          opening figure
                          opening axes
                          draw image of size 2848
+                         opening legend
+                         closing legend
                          closing axes
                          closing figure
                          """)
diff --git a/mplexporter/utils.py b/mplexporter/utils.py
index e444575..4bd1926 100644
--- a/mplexporter/utils.py
+++ b/mplexporter/utils.py
@@ -296,9 +296,13 @@ def get_axes_properties(ax):
         props[axname + 'domain'] = domain
 
     return props
-    
 
 
+def get_legend_properties(ax):
+    handles, labels = ax.get_legend_handles_labels()
+    return {'handles': handles, 'labels': labels}
+    
+
 def image_to_base64(image):
     """
     Convert a matplotlib image to a base64 png representation

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-mplexporter.git



More information about the Python-modules-commits mailing list