[Python-modules-commits] [python-mplexporter] 64/135: Added user_friendly dictionary repair functions to plotly_utils.

Wolfgang Borgert debacle at moszumanska.debian.org
Tue Sep 23 21:19:04 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 26fce2eea0418a264dbd2f5e6caed060732dc108
Author: theengineear <andseier at gmail.com>
Date:   Thu Feb 27 20:14:38 2014 -0800

    Added user_friendly dictionary repair functions to plotly_utils.
    
    There are many situations where and 'x1', 'y1', 'xaxis1', etc. show up
    in the final collections for layout or data.
    
    To make future fixes simpler the following system was put in place:
    
    - To rename a key add the following to the *_key_repairs dict:
    (key_path_tup): new_key
    
    - To repair a value add the following to the *_val_repairs dict:
    (key_path_tup): {bug: fix}
    
    'key_path_tup'** is a tuple of dictionary keys. 'new_key' is the key you
    would like to rename 'key_path_tuple[-1]' with. 'bug' is the value that
    needs to be changed to 'fix'.
    
    ** key_path_tup will work ACROSS lists that are nested within plotly
    JSON structures. For example, 'annotations' is a key in layout, but
    layout['annotations'] is a list of dictionaries. These new functions
    handle this inconsistency by splitting into a for loop each time this
    happens and continuing along the remaining key_path_tup for each
    dictionary in the list.
    
    PlotlyRenderer class was updated to use this new functionality.
---
 mplexporter/renderers/plotly/plotly_renderer.py | 42 ++++++++---------
 mplexporter/renderers/plotly/plotly_utils.py    | 63 +++++++++++++++++++++++++
 2 files changed, 84 insertions(+), 21 deletions(-)

diff --git a/mplexporter/renderers/plotly/plotly_renderer.py b/mplexporter/renderers/plotly/plotly_renderer.py
index 2a49ff6..d0c76f0 100644
--- a/mplexporter/renderers/plotly/plotly_renderer.py
+++ b/mplexporter/renderers/plotly/plotly_renderer.py
@@ -26,9 +26,15 @@ class PlotlyRenderer(Renderer):
 
     def close_figure(self, fig):
         self.output += "closing figure\n"
-        self.configure_primary_axes()  # changes 'y1', 'xaxis1', etc. to 'y', 'xaxis', etc.
+        plotly_utils.repair_data(self.data)
+        plotly_utils.repair_layout(self.layout)
         for data_dict in self.data:
             plotly_utils.clean_dict(data_dict)
+        try:
+            for annotation_dict in self.layout['annotations']:
+                plotly_utils.clean_dict(annotation_dict)
+        except KeyError:
+            pass
         plotly_utils.clean_dict(self.layout)
         self.layout['showlegend'] = False
 
@@ -102,26 +108,20 @@ class PlotlyRenderer(Renderer):
         else:
             self.output += "    received {} markers with 'figure' coordinates, skipping!".format(data.shape[0])
 
-    def configure_primary_axes(self):
-        for data_dict in self.data:
-            if 'xaxis' in data_dict and data_dict['xaxis'] == 'x1':
-                del data_dict['xaxis']
-            if 'yaxis' in data_dict and data_dict['yaxis'] == 'y1':
-                del data_dict['yaxis']
-        if 'xaxis1' in self.layout:
-            self.layout['xaxis'] = self.layout.pop('xaxis1')
-        if 'yaxis1' in self.layout:
-            self.layout['yaxis'] = self.layout.pop('yaxis1')
-        try:
-            if 'y1' in self.layout['xaxis']['anchor']:
-                self.layout['xaxis']['anchor'] = 'y'
-        except KeyError:
-            pass
-        try:
-            if 'x1' in self.layout['yaxis']['anchor']:
-                self.layout['yaxis']['anchor'] = 'x'
-        except KeyError:
-            pass
+    def draw_text(self, **props):
+        if 'annotations' not in self.layout:
+            self.layout['annotations'] = []
+        print 'new annotation: ', props['text']
+        annotation = {
+            'text': props['text'],
+            'font': {'color': props['style']['color'], 'size': props['style']['fontsize']},
+            'xref': 'x{}'.format(self.axis_ct),
+            'yref': 'y{}'.format(self.axis_ct)
+        }
+        print 'adding annotation dict:\n', annotation
+        self.layout['annotations'] += annotation,
+        # position=position, coordinates=coordinates, style=style, mplobj=text)
+
 
 def fig_to_plotly(fig, username=None, api_key=None, notebook=False):
     """Convert a matplotlib figure to plotly dictionary
diff --git a/mplexporter/renderers/plotly/plotly_utils.py b/mplexporter/renderers/plotly/plotly_utils.py
index 7440502..9c0a06c 100644
--- a/mplexporter/renderers/plotly/plotly_utils.py
+++ b/mplexporter/renderers/plotly/plotly_utils.py
@@ -35,6 +35,50 @@ def clean_dict(node, parent=None, node_key=None):
             del parent[node_key]
 
 
+def repair_key(d, key_path_tup, fix):
+    try:
+        for num, key in enumerate(key_path_tup[:-1]):
+            d = d[key]
+            if isinstance(d, list):
+                for sub_d in d:
+                    repair_key(sub_d, key_path_tup[num+1:], fix)
+        d[fix] = d.pop(key_path_tup[-1])
+    except KeyError:
+        pass
+    except TypeError:
+        pass
+
+
+def repair_val(d, key_path_tup, repair_dict):
+        try:
+            for num, key in enumerate(key_path_tup[:-1]):
+                d = d[key]
+                if isinstance(d, list):
+                    for sub_d in d:
+                        repair_val(sub_d, key_path_tup[num+1:], repair_dict)
+            for bug, fix in repair_dict.items():
+                if d[key_path_tup[-1]] == bug:
+                    d[key_path_tup[-1]] = fix
+        except KeyError:
+            pass
+        except TypeError:
+            pass
+
+
+def repair_data(data):
+    for data_dict in data:
+        for key_path_tup, fix in data_key_repairs.items():
+            repair_key(data_dict, key_path_tup, fix)
+        for key_path_tup, repair_dict in data_val_repairs.items():
+                repair_val(data_dict, key_path_tup, repair_dict)
+
+
+def repair_layout(layout):
+    for key_path_tup, fix in layout_key_repairs.items():
+        repair_key(layout, key_path_tup, fix)
+    for key_path_tup, repair_dict in layout_val_repairs.items():
+            repair_val(layout, key_path_tup, repair_dict)
+
 
 dash_map = {
     '10,0': 'solid',
@@ -58,4 +102,23 @@ symbol_map = {
     '-': 'solid',
     '--': 'dash',
     '-.': 'dashdot'
+}
+
+data_key_repairs = {}
+
+layout_key_repairs = {
+    ('xaxis1',): 'xaxis',
+    ('yaxis1',): 'yaxis'
+}
+
+data_val_repairs = {  # (1) keys with None get deleted, (2) empty dicts get deleted!
+    ('xaxis',): {'x1': None},
+    ('yaxis',): {'y1': None}
+}
+
+layout_val_repairs = {
+    ('xaxis', 'anchor'): {'y1': 'y'},
+    ('yaxis', 'anchor'): {'x1': 'x'},
+    ('annotations', 'xref'): {'x1': 'x'},
+    ('annotations', 'yref'): {'y1': 'y'}
 }
\ No newline at end of file

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