[Python-modules-commits] [python-mplexporter] 03/135: add basic vincent renderer

Wolfgang Borgert debacle at moszumanska.debian.org
Tue Sep 23 21:18:57 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 09bedd137f2e1de59b1812adefd27f3b8e9c6e70
Author: Jake Vanderplas <vanderplas at astro.washington.edu>
Date:   Sun Feb 16 20:18:36 2014 -0800

    add basic vincent renderer
---
 VincentTest.ipynb                              | 228 +++++++++++++++++++++++++
 mplexporter/__init__.py                        |   2 +-
 mplexporter/exporter.py                        |  19 ++-
 mplexporter/renderers/__init__.py              |   2 +
 mplexporter/renderers/_vincent.py              |  49 ++++++
 mplexporter/{renderer.py => renderers/base.py} |   0
 mplexporter/tests/test_basic.py                |   2 +-
 7 files changed, 299 insertions(+), 3 deletions(-)

diff --git a/VincentTest.ipynb b/VincentTest.ipynb
new file mode 100644
index 0000000..4a649d5
--- /dev/null
+++ b/VincentTest.ipynb
@@ -0,0 +1,228 @@
+{
+ "metadata": {
+  "name": ""
+ },
+ "nbformat": 3,
+ "nbformat_minor": 0,
+ "worksheets": [
+  {
+   "cells": [
+    {
+     "cell_type": "heading",
+     "level": 1,
+     "metadata": {},
+     "source": [
+      "Vincent Test"
+     ]
+    },
+    {
+     "cell_type": "markdown",
+     "metadata": {},
+     "source": [
+      "This notebook shows a simple example of using the vincent renderer to \n",
+      "convert a simple matplotlib plot to [vega](http://trifacta.github.io/vega/)\n",
+      "via the [vincent](https://vincent.readthedocs.org) package.\n",
+      "\n",
+      "This converter is still very incomplete, and will be improved with time."
+     ]
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "import matplotlib.pyplot as plt\n",
+      "import numpy as np"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [],
+     "prompt_number": 1
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "%matplotlib inline"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [],
+     "prompt_number": 2
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "import vincent\n",
+      "vincent.core.initialize_notebook()"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [
+      {
+       "html": [
+        "<script>\n",
+        "    if (window['d3'] === undefined) {\n",
+        "        require.config({ paths: {d3: \"http://d3js.org/d3.v3.min\"} });\n",
+        "        require([\"d3\"], function(d3) {\n",
+        "          window.d3 = d3;\n",
+        "          $.getScript(\"http://d3js.org/d3.geo.projection.v0.min.js\", function() {\n",
+        "        $.getScript(\"http://wrobstory.github.io/d3-cloud/d3.layout.cloud.js\", function() {\n",
+        "            $.getScript(\"http://d3js.org/topojson.v1.min.js\", function() {\n",
+        "                $.getScript(\"http://trifacta.github.com/vega/vega.js\", function() {\n",
+        "                        $([IPython.events]).trigger(\"vega_loaded.vincent\");\n",
+        "                })\n",
+        "            })\n",
+        "        })\n",
+        "    });\n",
+        "        });\n",
+        "    };\n",
+        "    if (window['topojson'] === undefined) {\n",
+        "        require.config(\n",
+        "            { paths: {topojson: \"http://d3js.org/topojson.v1.min\"} }\n",
+        "            );\n",
+        "        require([\"topojson\"], function(topojson) {\n",
+        "          window.topojson = topojson;\n",
+        "        });\n",
+        "    };\n",
+        "    </script>"
+       ],
+       "metadata": {},
+       "output_type": "display_data",
+       "text": [
+        "<IPython.core.display.HTML at 0x106214110>"
+       ]
+      }
+     ],
+     "prompt_number": 3
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "from IPython.display import display, HTML\n",
+      "from vincent.visualization import _vega_t\n",
+      "import random\n",
+      "\n",
+      "def display_natural(obj):\n",
+      "    \"\"\"\n",
+      "    Display a vincent object in IPython\n",
+      "    without forcing it to 100% of the page width\n",
+      "    \"\"\"\n",
+      "    # the following is adapted from Visualization._repr_html_\n",
+      "    id = random.randint(0, 2 ** 16)\n",
+      "    html = '<div id=\"vis%d\"></div>' % id\n",
+      "    html += '<script>\\n'\n",
+      "    html += _vega_t % (obj.to_json(pretty_print=False), id) + '\\n'\n",
+      "    html += '</script>\\n'\n",
+      "    return HTML(html)"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [],
+     "prompt_number": 4
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "from mplexporter.renderers import fig_to_vincent"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [],
+     "prompt_number": 5
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "x = np.linspace(0, 10, 100)\n",
+      "y = np.sin(x)\n",
+      "\n",
+      "fig, ax = plt.subplots()\n",
+      "ax.plot(x, y)\n",
+      "\n",
+      "display_natural(fig_to_vincent(fig))"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [
+      {
+       "html": [
+        "<div id=\"vis13979\"></div><script>\n",
+        "\n",
+        "( function() {\n",
+        "  var _do_plot = function() {\n",
+        "    if ( (typeof vg == 'undefined') && (typeof IPython != 'undefined')) {\n",
+        "      $([IPython.events]).on(\"vega_loaded.vincent\", _do_plot);\n",
+        "      return;\n",
+        "    }\n",
+        "    vg.parse.spec({\"axes\": [{\"scale\": \"x\", \"type\": \"x\"}, {\"scale\": \"y\", \"type\": \"y\"}], \"data\": [{\"name\": \"table\", \"values\": [{\"col\": \"y\", \"idx\": 0.0, \"val\": 0.0}, {\"col\": \"y\", \"idx\": 0.10101010101010101, \"val\": 0.10083842025810461}, {\"col\": \"y\", \"idx\": 0.20202020202020202, \"val\": 0.20064885652268541}, {\"col\": \"y\", \"idx\": 0.30303030303030304, \"val\": 0.2984138044476411}, {\"col\": \"y\", \"idx\": 0.40404040404040403, \"val\ [...]
+        "      chart({el: \"#vis13979\"}).update();\n",
+        "    });\n",
+        "  };\n",
+        "  _do_plot();\n",
+        "})();\n",
+        "\n",
+        "</script>\n"
+       ],
+       "metadata": {},
+       "output_type": "pyout",
+       "prompt_number": 6,
+       "text": [
+        "<IPython.core.display.HTML at 0x105f61f10>"
+       ]
+      }
+     ],
+     "prompt_number": 6
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "x = np.random.random(50)\n",
+      "y = np.random.random(50)\n",
+      "\n",
+      "fig, ax = plt.subplots()\n",
+      "ax.plot(x, y, 'or')\n",
+      "\n",
+      "display_natural(fig_to_vincent(fig))"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": [
+      {
+       "html": [
+        "<div id=\"vis49955\"></div><script>\n",
+        "\n",
+        "( function() {\n",
+        "  var _do_plot = function() {\n",
+        "    if ( (typeof vg == 'undefined') && (typeof IPython != 'undefined')) {\n",
+        "      $([IPython.events]).on(\"vega_loaded.vincent\", _do_plot);\n",
+        "      return;\n",
+        "    }\n",
+        "    vg.parse.spec({\"axes\": [{\"scale\": \"x\", \"type\": \"x\"}, {\"scale\": \"y\", \"type\": \"y\"}], \"data\": [{\"name\": \"table\", \"values\": [{\"col\": \"y\", \"idx\": 0.80353589888620203, \"val\": 0.80115708889368742}, {\"col\": \"y\", \"idx\": 0.31049233307855506, \"val\": 0.55949939420633477}, {\"col\": \"y\", \"idx\": 0.14474598815449047, \"val\": 0.6038448274580166}, {\"col\": \"y\", \"idx\": 0.268781448824022, \"val\": 0.93918421327231294}, {\"col\": \"y\", \"idx\ [...]
+        "      chart({el: \"#vis49955\"}).update();\n",
+        "    });\n",
+        "  };\n",
+        "  _do_plot();\n",
+        "})();\n",
+        "\n",
+        "</script>\n"
+       ],
+       "metadata": {},
+       "output_type": "pyout",
+       "prompt_number": 7,
+       "text": [
+        "<IPython.core.display.HTML at 0x10715e150>"
+       ]
+      }
+     ],
+     "prompt_number": 7
+    }
+   ],
+   "metadata": {}
+  }
+ ]
+}
\ No newline at end of file
diff --git a/mplexporter/__init__.py b/mplexporter/__init__.py
index daa22df..5b0485c 100644
--- a/mplexporter/__init__.py
+++ b/mplexporter/__init__.py
@@ -1,2 +1,2 @@
-from renderer import Renderer
+from renderers import Renderer
 from exporter import Exporter
diff --git a/mplexporter/exporter.py b/mplexporter/exporter.py
index 05fa21f..e4a4545 100644
--- a/mplexporter/exporter.py
+++ b/mplexporter/exporter.py
@@ -8,10 +8,27 @@ from . import utils
 
 
 class Exporter(object):
-    def __init__(self, renderer):
+    """Matplotlib Exporter
+
+    Parameters
+    ----------
+    renderer : Renderer object
+        The render processes the Exporter output to create a visualization of
+        a figure.
+    close_mpl : bool
+        If True (default), close the matplotlib figure as it is rendered. This
+        is useful for when the exporter is used within the notebook, or with
+        an interactive matplotlib backend.
+    """
+
+    def __init__(self, renderer, close_mpl=True):
+        self.close_mpl = close_mpl
         self.renderer = renderer
 
     def run(self, fig):
+        if self.close_mpl:
+            import matplotlib.pyplot as plt
+            plt.close(fig)
         self._crawl_fig(fig)
 
     def _process_transform(self, transform, ax=None, data=None):
diff --git a/mplexporter/renderers/__init__.py b/mplexporter/renderers/__init__.py
new file mode 100644
index 0000000..8dc28ec
--- /dev/null
+++ b/mplexporter/renderers/__init__.py
@@ -0,0 +1,2 @@
+from .base import Renderer
+from ._vincent import VincentRenderer, fig_to_vincent
diff --git a/mplexporter/renderers/_vincent.py b/mplexporter/renderers/_vincent.py
new file mode 100644
index 0000000..1cd9cd5
--- /dev/null
+++ b/mplexporter/renderers/_vincent.py
@@ -0,0 +1,49 @@
+import warnings
+from .base import Renderer
+from ..exporter import Exporter
+
+
+class VincentRenderer(Renderer):
+    def open_figure(self, fig):
+        self.chart = None
+        self.figwidth = int(fig.get_figwidth() * fig.dpi)
+        self.figheight = int(fig.get_figheight() * fig.dpi)
+
+    def draw_line(self, data, coordinates, style):
+        import vincent
+        if coordinates != 'data':
+            warnings.warn("Only data coordinates supported. Skipping this")
+        linedata = {'x': data[:, 0],
+                    'y': data[:, 1]}
+        line = vincent.Line(linedata, iter_idx='x',
+                            width=self.figwidth, height=self.figheight)
+        line.scales['color'].range = [style['color']]
+
+        # TODO: set the 
+
+        if self.chart is None:
+            self.chart = line
+        else:
+            warnings.warn("Multiple plot elements not yet supported")
+
+    def draw_markers(self, data, coordinates, style):
+        import vincent
+        if coordinates != 'data':
+            warnings.warn("Only data coordinates supported. Skipping this")
+        markerdata = {'x': data[:, 0],
+                      'y': data[:, 1]}
+        markers = vincent.Scatter(markerdata, iter_idx='x',
+                                  width=self.figwidth, height=self.figheight)
+        markers.scales['color'].range = [style['facecolor']]
+        if self.chart is None:
+            self.chart = markers
+        else:
+            warnings.warn("Multiple plot elements not yet supported")
+
+
+def fig_to_vincent(fig):
+    """Convert a matplotlib figure to a vincent object"""
+    renderer = VincentRenderer()
+    exporter = Exporter(renderer)
+    exporter.run(fig)
+    return renderer.chart
diff --git a/mplexporter/renderer.py b/mplexporter/renderers/base.py
similarity index 100%
rename from mplexporter/renderer.py
rename to mplexporter/renderers/base.py
diff --git a/mplexporter/tests/test_basic.py b/mplexporter/tests/test_basic.py
index 01bcc04..cb51f19 100644
--- a/mplexporter/tests/test_basic.py
+++ b/mplexporter/tests/test_basic.py
@@ -1,5 +1,5 @@
 from ..exporter import Exporter
-from ..renderer import Renderer
+from ..renderers import Renderer
 
 import matplotlib
 matplotlib.use('Agg')

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