[Python-modules-commits] [python-mplexporter] 83/135: Removed plotly subpackage from mplexporter package.
Wolfgang Borgert
debacle at moszumanska.debian.org
Tue Sep 23 21:19:06 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 f891fe9c3709a5bc8449b6258bef27947e770ecf
Author: theengineear <andseier at gmail.com>
Date: Sat Mar 8 17:04:21 2014 -0800
Removed plotly subpackage from mplexporter package.
Implementation for plotly can now be found at:
https://github.com/mpld3/matplotlylib
---
examples/plotly_example.py | 55 ----
mplexporter/renderers/plotly/__init__.py | 1 -
mplexporter/renderers/plotly/plotly_renderer.py | 340 ------------------------
mplexporter/renderers/plotly/plotly_utils.py | 235 ----------------
mplexporter/tests/test_plotly.py | 179 -------------
notebooks/PlotlyTest.ipynb | 222 ----------------
6 files changed, 1032 deletions(-)
diff --git a/examples/plotly_example.py b/examples/plotly_example.py
deleted file mode 100644
index 372712d..0000000
--- a/examples/plotly_example.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from mplexporter.renderers import PlotlyRenderer, fig_to_plotly
-import numpy as np
-import matplotlib.pyplot as plt
-import matplotlib.gridspec as gridspec
-username = 'IPython.Demo'
-api_key = '1fw3zw2o13'
-
-
-def plot_sin():
- # setup matplotlib plot
- x = np.arange(0,1.0,0.01)
- y1 = np.sin(2*np.pi*x)
- y2 = np.cos(4*np.pi*x)
- plt.plot(x, y1, 'b--', label='sin')
- plt.plot(x, y2, 'go', label='cos')
- plt.title("It's a Sign")
- plt.xlabel('time')
- plt.ylabel('amplitude')
- plt.legend().set_visible(True)
-
- # export info from matplotlib fig and render with plotly!
- fig = plt.gcf()
- fig_to_plotly(fig, username, api_key)
-
-
-def two_plots():
- plt.figure(1)
- plt.subplot(211)
- plt.plot([1,2,3],[4,5,6])
- plt.subplot(212)
- plt.plot([1,2,3],[3,6,2])
- plt.title('two subplots')
-
- fig = plt.gcf()
- fig_to_plotly(fig, username, api_key)
-
-
-def four_plots():
- fig = plt.figure() # matplotlib.figure.Figure obj
- gs = gridspec.GridSpec(3, 3)
- ax1 = fig.add_subplot(gs[0,:])
- ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
- ax2 = fig.add_subplot(gs[1,:-1])
- ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
- ax3 = fig.add_subplot(gs[1:, 2])
- ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
- ax4 = fig.add_subplot(gs[2,0])
- ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
- ax5 = fig.add_subplot(gs[2,1])
- ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
- gs.update(hspace=0.5, wspace=0.5)
- fig_to_plotly(fig, username, api_key)
-
-if __name__ == '__main__':
- four_plots()
diff --git a/mplexporter/renderers/plotly/__init__.py b/mplexporter/renderers/plotly/__init__.py
deleted file mode 100644
index 342da70..0000000
--- a/mplexporter/renderers/plotly/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .plotly_renderer import PlotlyRenderer, fig_to_plotly
\ No newline at end of file
diff --git a/mplexporter/renderers/plotly/plotly_renderer.py b/mplexporter/renderers/plotly/plotly_renderer.py
deleted file mode 100644
index d2d7a90..0000000
--- a/mplexporter/renderers/plotly/plotly_renderer.py
+++ /dev/null
@@ -1,340 +0,0 @@
-"""
-Plotly Renderer.
-
-A renderer class to be used with an exporter for rendering matplotlib plots
-in Plotly.
-
-Attributes:
- PlotlyRenderer -- a renderer class to be used with an Exporter obj
- fig_to_plotly -- a function to send an mpl figure to Plotly
-
-"""
-from . import plotly_utils
-from .. base import Renderer
-from ... exporter import Exporter
-
-
-class PlotlyRenderer(Renderer):
- """A renderer class inheriting from base for rendering mpl plots in plotly.
-
- Attributes:
- username -- plotly username, required for fig_to_plotly (default None)
- api_key -- api key for given plotly username (defualt None)
- data -- a list of data dictionaries to be passed to plotly
- layout -- a layout dictionary to be passed to plotly
- axis_ct -- a reference to the number of axes rendered from mpl fig
-
- Inherited Methods (see renderers.base):
- ax_zoomable(ax) -- static method
- ax_has_xgrid(ax) -- static method
- ax_has_ygrid(ax) -- static method
- current_ax_zoomable(self) -- property
- current_ax_has_xgrid(self) -- property
- current_ax_has_ygrid(self) -- property
- draw_figure(self, fig, props) -- context manager
- draw_axes(self, ax, props) -- context manager
-
- Reimplemented Methods (see renderers.base):
- open_figure(self, fig, props)
- close_figure(self, fig)
- open_axes(self, ax, props)
- close_axes(self, ax)
- draw_line(self, **props)
- draw_markers(self, **props)
- draw_text(self, **props)
-
- """
- def __init__(self, username=None, api_key=None):
- """Initialize PlotlyRenderer obj.
-
- PlotlyRenderer obj is called on by an Exporter object to draw
- matplotlib objects like figures, axes, text, etc.
-
- """
- self.username = username
- self.api_key = api_key
- self.data = []
- self.layout = {}
- self.axis_ct = 0
-
- def open_figure(self, fig, props):
- """Creates a new figure by beginning to fill out layout dict.
-
- Currently, margins are set to zero to reconcile differences between
- mpl and plotly without complicated transforms. This will be changed
- in future revisions. Autosize is set to false so that the figure will
- mirror sizes set by mpl.
-
- """
- self.layout['width'] = int(props['figwidth']*props['dpi'])
- self.layout['height'] = int(props['figheight']*props['dpi'])
- self.layout['margin'] = {'l': 0, 'r': 0, 't': 0, 'b': 0, 'pad': 0}
- self.layout['autosize'] = False
-
- def close_figure(self, fig):
- """Closes figure by cleaning up data and layout dictionaries.
-
- The PlotlyRenderer's job is to create an appropriate set of data and
- layout dictionaries. When the figure is closed, some cleanup and
- repair is necessary. This method removes inappropriate dictionary
- entries, freeing up Plotly to use defaults and best judgements to
- complete the entries. This method is called by an Exporter object.
-
- Positional arguments:
- fig -- an mpl figure object.
-
- """
- 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
-
- def open_axes(self, ax, props):
- """Setup a new axes object (subplot in plotly).
-
- Plotly stores information about subplots in different 'xaxis' and
- 'yaxis' objects which are numbered. These are just dictionaries
- included in the layout dictionary. This function takes information
- from the Exporter, fills in appropriate dictionary entries,
- and updates the layout dictionary. PlotlyRenderer keeps track of the
- number of plots by incrementing the axis_ct attribute.
-
- Positional arguments:
- ax -- an mpl axes object. This will become a subplot in plotly.
- props -- selected axes properties from the exporter (a dict).
-
- """
- self.axis_ct += 1
- layout = {
- 'xaxis{}'.format(self.axis_ct): {
- 'range': props['xlim'],
- 'showgrid': props['axes'][1]['grid']['gridOn'],
- 'domain': plotly_utils.get_x_domain(props['bounds']),
- 'anchor': 'y{}'.format(self.axis_ct)
- },
- 'yaxis{}'.format(self.axis_ct): {
- 'range': props['ylim'],
- 'showgrid': props['axes'][0]['grid']['gridOn'],
- 'domain': plotly_utils.get_y_domain(props['bounds']),
- 'anchor': 'x{}'.format(self.axis_ct)
- }
- }
- for key, value in layout.items():
- self.layout[key] = value
-
- def close_axes(self, ax):
- """Close the axes object and clean up."""
- pass
-
- def draw_line(self, **props):
- """Create a data dict for a line obj.
-
- Props dict (key: value):
- 'coordinates': 'data', 'axes', 'figure', or 'display'.
- 'data': a list of xy pairs.
- 'style': style dict from utils.get_line_style
- 'mplobj': an mpl object, in this case the line object.
-
- """
- if props['coordinates'] == 'data':
- trace = {
- 'mode': 'lines',
- 'x': [xy_pair[0] for xy_pair in props['data']],
- 'y': [xy_pair[1] for xy_pair in props['data']],
- 'xaxis': 'x{}'.format(self.axis_ct),
- 'yaxis': 'y{}'.format(self.axis_ct),
- 'line': {
- 'opacity': props['style']['alpha'],
- 'color': props['style']['color'],
- 'width': props['style']['linewidth'],
- 'dash': plotly_utils.convert_dash(props['style'][
- 'dasharray'])
- }
- }
- self.data += trace,
- else:
- pass
-
- def draw_markers(self, **props):
- """Create a data dict for a line obj using markers.
-
- Props dict (key: value):
- 'coordinates': 'data', 'axes', 'figure', or 'display'.
- 'data': a list of xy pairs.
- 'style': style dict from utils.get_marker_style
- 'mplobj': an mpl object, in this case the line object.
-
- """
- if props['coordinates'] == 'data':
- trace = {
- 'mode': 'markers',
- 'x': [xy_pair[0] for xy_pair in props['data']],
- 'y': [xy_pair[1] for xy_pair in props['data']],
- 'xaxis': 'x{}'.format(self.axis_ct),
- 'yaxis': 'y{}'.format(self.axis_ct),
- 'marker': {
- 'opacity': props['style']['alpha'],
- 'color': props['style']['facecolor'],
- 'symbol': plotly_utils.convert_symbol(props['style'][
- 'marker']),
- 'line': {
- 'color': props['style']['edgecolor'],
- 'width': props['style']['edgewidth']
- }
- }
- }
- # not sure whether we need to incorporate style['markerpath']
- self.data += trace,
- else:
- pass
-
- def draw_text(self, **props):
- """Create an annotation dict for a text obj.
-
- Currently, plotly uses either 'page' or 'data' to reference
- annotation locations. These refer to 'display' and 'data',
- respectively for the 'coordinates' key used in the Exporter.
- Appropriate measures are taken to transform text locations to
- reference one of these two options.
-
- Props dict (key: value):
- 'coordinates': reference for position, 'data', 'axes', 'figure', etc.
- 'position': x,y location of text in the given coordinates.
- 'style': style dict from utils.get_text_style.
- 'text': actual string content.
-
- """
- if 'annotations' not in self.layout:
- self.layout['annotations'] = []
- if props['text_type'] == 'xlabel':
- self.draw_xlabel(**props)
- elif props['text_type'] == 'ylabel':
- self.draw_ylabel(**props)
- elif props['text_type'] == 'title':
- self.draw_title(**props)
- else: # just a regular text annotation...
- if True: # props['coordinates'] is not 'data':
- x_px, y_px = props['mplobj'].get_transform().transform(
- props['position'])
- x, y = plotly_utils.convert_to_paper(x_px, y_px, self.layout)
- xref = 'paper'
- yref = 'paper'
- else:
- x, y = props['position']
- xref = 'x{}'.format(self.axis_ct)
- yref = 'y{}'.format(self.axis_ct)
- annotation = {
- 'text': props['text'],
- 'x': x,
- 'y': y,
- 'xref': xref,
- 'yref': yref,
- 'font': {'color': props['style']['color'],
- 'size': props['style']['fontsize']
- },
- 'showarrow': False # change this later?
- }
- self.layout['annotations'] += annotation,
-
- def draw_title(self, **props):
- """Add a title to the current subplot in layout dictionary.
-
- Currently, titles are added as annotations.
-
- """
- x_px, y_px = props['mplobj'].get_transform().transform(props[
- 'position'])
- x, y = plotly_utils.convert_to_paper(x_px, y_px, self.layout)
- annotation = {
- 'text': props['text'],
- 'font': {'color': props['style']['color'],
- 'size': props['style']['fontsize']
- },
- 'xref': 'paper',
- 'yref': 'paper',
- 'x': x,
- 'y': y,
- 'showarrow': False # no arrow for a title!
- }
- self.layout['annotations'] += annotation,
-
- def draw_xlabel(self, **props):
- """Add an xaxis label to the current subplot in layout dictionary."""
- self.layout['xaxis{}'.format(self.axis_ct)]['title'] = props['text']
- titlefont = {'size': props['style']['fontsize'],
- 'color': props['style']['color']
- }
- self.layout['xaxis{}'.format(self.axis_ct)]['titlefont'] = titlefont
-
- def draw_ylabel(self, **props):
- """Add a yaxis label to the current subplot in layout dictionary."""
- self.layout['yaxis{}'.format(self.axis_ct)]['title'] = props['text']
- titlefont = {'size': props['style']['fontsize'],
- 'color': props['style']['color']
- }
- self.layout['yaxis{}'.format(self.axis_ct)]['titlefont'] = titlefont
-
-
-def fig_to_plotly(fig, username=None, api_key=None, notebook=False):
- """Convert a matplotlib figure to plotly dictionary and send.
-
- All available information about matplotlib visualizations are stored
- within a matplotlib.figure.Figure object. You can create a plot in python
- using matplotlib, store the figure object, and then pass this object to
- the fig_to_plotly function. In the background, mplexporter is used to
- crawl through the mpl figure object for appropriate information. This
- information is then systematically sent to the PlotlyRenderer which
- creates the JSON structure used to make plotly visualizations. Finally,
- these dictionaries are sent to plotly and your browser should open up a
- new tab for viewing! Optionally, if you're working in IPython, you can
- set notebook=True and the PlotlyRenderer will call plotly.iplot instead
- of plotly.plot to have the graph appear directly in the IPython notebook.
-
- Note, this function gives the user access to a simple, one-line way to
- render an mpl figure in plotly. If you need to trouble shoot, you can do
- this step manually by NOT running this fuction and entereing the following:
-
- ============================================================================
- from mplexporter import Exporter
- from mplexporter.renderers import PlotlyRenderer
-
- # create an mpl figure and store it under a varialble 'fig'
-
- renderer = PlotlyRenderer()
- exporter = Exporter(renderer)
- exporter.run(fig)
- ============================================================================
-
- You can then inspect the JSON structures by accessing these:
-
- renderer.layout -- a plotly layout dictionary
- renderer.data -- a list of plotly data dictionaries
-
- Positional arguments:
- fig -- a matplotlib figure object
- username -- a valid plotly username **
- api_key -- a valid api_key for the above username **
- notebook -- an option for use with an IPython notebook
-
- ** Don't have a username/api_key? Try looking here:
- https://plot.ly/plot
-
- ** Forgot your api_key? Try signing in and looking here:
- https://plot.ly/api/python/getting-started
-
- """
- import plotly
- renderer = PlotlyRenderer(username=username, api_key=api_key)
- Exporter(renderer).run(fig)
- py = plotly.plotly(renderer.username, renderer.api_key)
- if notebook:
- return py.iplot(renderer.data, layout=renderer.layout)
- else:
- py.plot(renderer.data, layout=renderer.layout)
diff --git a/mplexporter/renderers/plotly/plotly_utils.py b/mplexporter/renderers/plotly/plotly_utils.py
deleted file mode 100644
index 659ca39..0000000
--- a/mplexporter/renderers/plotly/plotly_utils.py
+++ /dev/null
@@ -1,235 +0,0 @@
-def convert_symbol(mpl_symbol):
- """Convert mpl marker symbol to plotly symbol and return symbol."""
- if mpl_symbol in SYMBOL_MAP:
- return SYMBOL_MAP[mpl_symbol]
- else:
- return 'dot' # default
-
-
-def convert_dash(mpl_dash):
- """Convert mpl line symbol to plotly line symbol and return symbol."""
- if mpl_dash in DASH_MAP:
- return DASH_MAP[mpl_dash]
- else:
- return 'solid' # default
-
-
-def get_x_domain(bounds):
- """Convert matplotlib (x0,width) to (x0,x1) and return."""
- return [bounds[0], bounds[0] + bounds[2]]
-
-
-def get_y_domain(bounds):
- """Convert matplotlib (y0,height) to (y0,y1) and return."""
- return [bounds[1], bounds[1] + bounds[3]]
-
-
-def convert_to_paper(x, y, layout):
- """Convert mpl display coordinates to plotly paper coordinates.
-
- Plotly references object positions with an (x, y) coordinate pair in either
- 'data' or 'paper' coordinates which reference actual data in a plot or
- the entire plotly axes space where the bottom-left of the bottom-left
- plot has the location (x, y) = (0, 0) and the top-right of the top-right
- plot has the location (x, y) = (1, 1). Display coordinates in mpl reference
- objects with an (x, y) pair in pixel coordinates, where the bottom-left
- corner is at the location (x, y) = (0, 0) and the top-right corner is at
- the location (x, y) = (figwidth*dpi, figheight*dpi). Here, figwidth and
- figheight are in inches and dpi are the dots per inch resolution.
-
- """
- num_x = x - layout['margin']['l']
- den_x = layout['width'] - (layout['margin']['l'] + layout['margin']['r'])
- num_y = y - layout['margin']['b']
- den_y = layout['height'] - (layout['margin']['b'] + layout['margin']['t'])
- return num_x/den_x, num_y/den_y
-
-
-def clean_dict(node, parent=None, node_key=None):
- """Remove None, 'none', 'None', and {} from a dictionary obj.
-
- When Plotly JSON dictionary entries are populated, Plotly will
- automatically fill in necessary items with defaults. However, if a
- nonsense entry is sent to plotly, it won't know to deal with it. This
- function removes some common 'nonsense' entries like empty dicts, None,
- 'None', or 'none'.
-
- The clean_dict function will typically be called with a dictionary
- argument only, allowing parent and node_key to remain defaults. The
- choice of node reflects that this function works recursively.
-
- Positional arguments:
- node -- a dictionary that needs to be cleaned
-
- Keyword arguments:
- parent -- the dictionary that contains node (default None)
- node_key -- parent[node_key] == node (default None)
-
- """
- del_keys = []
- for key, item in node.items():
- if isinstance(item, dict):
- clean_dict(item, node, key)
- else:
- if item in [None, 'none', 'None']:
- del_keys += [key]
- for key in del_keys:
- del node[key]
- if parent is not None:
- if len(node) == 0:
- del parent[node_key]
-
-
-def repair_key(d, key_path_tup, fix):
- """Repairs inappropriate keys caused by referencing self.ax_ct.
-
- This function allows inappropriate keys to be used in the
- PlotlyRenderer.layout and PlotlyRenderer.data dictionaries. This is done
- for the following reasons:
-
- - Code is made simpler by treating 1st axes instance the same as
- subsequent axes instances.
- - If future releases of Plotly accept keys such as 'xaxis1' or 'yaxis1',
- plotly_renderer.py and plolty_utils.py can be updated simply.
-
- Dictionaries need not be continuous for use with a key_path_tup. For
- example, layout['annotations'] is actually a list of annotation
- dictionaries. When repair_key() runs into such a list, it assumes that
- the list is populated by dictionaries and continues down the rest of the
- key_path_tup for each dictionary in the list.
-
- Positional arguments:
- d -- a plotly layout or data dictionary
- key_path_tup -- a tuple of dictionary keys that leads to the conflict
- fix -- the appropriate dictionary key for the key_path_tup
-
- """
- 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):
- """Repairs inappropriate values caused by referencing self.ax_ct.
-
- This function allows inappropriate values to be used in the
- PlotlyRenderer.layout and PlotlyRenderer.data dictionaries. This is done
- for the following reasons:
-
- - Code is made simpler by treating 1st axes instance the same as
- subsequent axes instances.
- - If future releases of Plotly accept values such as 'x1' or 'y1',
- plotly_renderer.py and plolty_utils.py can be updated simply.
-
- Dictionaries need not be continuous for use with a key_path_tup. For
- example, layout['annotations'] is actually a list of annotation
- dictionaries. When repair_val() runs into such a list, it assumes that
- the list is populated by dictionaries and continues down the rest of the
- key_path_tup for each dictionary in the list.
-
- Positional arguments:
- d -- a plotly layout or data dictionary
- key_path_tup -- a tuple of dictionary keys that leads to the conflict
- repair_dict -- a dictionary that contains {bad_value: good_value} entries
-
- """
- 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):
- """Fixes innapropriate keys and values in plotly data list.
-
- This function calls repair_key() and repair_val() for each entry in
- DATA_KEY_REPAIRS and DATA_VAL_REPAIRS. It assumes that the keys in these
- dictionaries are tuples with paths to known possible errors.
-
- Positional arguments:
- data -- a list of plotly data dictionaries
-
- """
- 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):
- """Fixes innapropriate keys and values in plotly layout dict.
-
- This function calls repair_key() and repair_val() for each entry in
- LAYOUT_KEY_REPAIRS and LAYOUT_VAL_REPAIRS. It assumes that the keys in
- these dictionaries are tuples with paths to known possible errors.
-
- Positional arguments:
- layout -- a plotly layout dictionary
-
- """
- 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',
- '6,6': 'dash',
- '2,2': 'dot',
- '4,4,2,4': 'dashdot',
- 'none': 'solid'
-}
-
-SYMBOL_MAP = {
- 'o': 'dot',
- 'v': 'triangle-down',
- '^': 'triangle-up',
- '<': 'triangle-left',
- '>': 'triangle-right',
- 's': 'square',
- '+': 'cross',
- 'x': 'x',
- 'D': 'diamond',
- 'd': 'diamond',
- '-': 'solid',
- '--': 'dash',
- '-.': 'dashdot'
-}
-
-DATA_KEY_REPAIRS = {}
-
-LAYOUT_KEY_REPAIRS = {
- ('xaxis1',): 'xaxis',
- ('yaxis1',): 'yaxis'
-}
-
-DATA_VAL_REPAIRS = {
- ('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
diff --git a/mplexporter/tests/test_plotly.py b/mplexporter/tests/test_plotly.py
deleted file mode 100644
index 790db1c..0000000
--- a/mplexporter/tests/test_plotly.py
+++ /dev/null
@@ -1,179 +0,0 @@
-from ..exporter import Exporter
-from ..renderers import PlotlyRenderer
-
-import matplotlib
-matplotlib.use('Agg')
-import matplotlib.pyplot as plt
-import matplotlib.gridspec as gridspec
-import numbers
-
-
-def test_simple_line():
- fig, ax = plt.subplots()
- ax.plot(range(10), '-k')
- ax.plot(range(5), '.k')
-
- renderer = PlotlyRenderer()
- exporter = Exporter(renderer)
- exporter.run(fig)
- for data_no, data_dict in enumerate(renderer.data):
- equivalent, msg = compare_dict(data_dict, SIMPLE_LINE['data'][data_no])
- assert equivalent, msg
- equivalent, msg = compare_dict(renderer.layout, SIMPLE_LINE['layout'])
- assert equivalent, msg
-
-
-def test_subplots():
- fig = plt.figure() # matplotlib.figure.Figure obj
- gs = gridspec.GridSpec(3, 3)
- ax1 = fig.add_subplot(gs[0,:])
- ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
- ax2 = fig.add_subplot(gs[1,:-1])
- ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
- ax3 = fig.add_subplot(gs[1:, 2])
- ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
- ax4 = fig.add_subplot(gs[2,0])
- ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
- ax5 = fig.add_subplot(gs[2,1])
- ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
-
- renderer = PlotlyRenderer()
- exporter = Exporter(renderer)
- exporter.run(fig)
- for data_no, data_dict in enumerate(renderer.data):
- equivalent, msg = compare_dict(data_dict, SUBPLOTS['data'][data_no])
- assert equivalent, msg
- equivalent, msg = compare_dict(renderer.layout, SUBPLOTS['layout'])
- assert equivalent, msg
-
-
-def compare_dict(dict1, dict2, equivalent=True, msg='', tol_digits=10):
- for key in dict1:
- if key not in dict2:
- return False, "{} not {}".format(dict1.keys(), dict2.keys())
- for key in dict1:
- if isinstance(dict1[key], dict):
- equivalent, msg = compare_dict(dict1[key], dict2[key], tol_digits=tol_digits)
- else:
- if not (dict1[key] == dict2[key]):
- return False, "['{}'] = {} not {}".format(key, dict1[key], dict2[key])
- if not equivalent:
- return False, "['{}']".format(key) + msg
- return equivalent, msg
-
-
-## dictionaries for tests
-
-SIMPLE_LINE = {
- 'data': [{'line': {'color': '#000000', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
- 'xaxis': 'x',
- 'y': [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
- 'yaxis': 'y'},
- {'marker': {'color': '#000000', 'line': {'color': '#000000', 'width': 0.5},
- 'opacity': 1,
- 'symbol': 'dot'},
- 'mode': 'markers',
- 'x': [0.0, 1.0, 2.0, 3.0, 4.0],
- 'xaxis': 'x',
- 'y': [0.0, 1.0, 2.0, 3.0, 4.0],
- 'yaxis': 'y'}],
- 'layout': {'height': 480,
- 'showlegend': False,
- 'title': '',
- 'width': 640,
- 'xaxis': {'domain': [0.125, 0.90000000000000002],
- 'range': (0.0, 9.0),
- 'showgrid': False,
- 'title': '',
- 'anchor': 'y'},
- 'yaxis': {'domain': [0.099999999999999978, 0.90000000000000002],
- 'range': (0.0, 9.0),
- 'showgrid': False,
- 'title': '',
- 'anchor': 'x'}}
-}
-
-SUBPLOTS = {'data': [{'line': {'color': '#FF0000', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [1.0, 2.0, 3.0, 4.0, 5.0],
- 'y': [10.0, 5.0, 10.0, 5.0, 10.0]},
- {'line': {'color': '#000000', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [1.0, 2.0, 3.0, 4.0],
- 'xaxis': 'x2',
- 'y': [1.0, 4.0, 9.0, 16.0],
- 'yaxis': 'y2'},
- {'line': {'color': '#0000FF', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [1.0, 2.0, 3.0, 4.0],
- 'xaxis': 'x3',
- 'y': [1.0, 10.0, 100.0, 1000.0],
- 'yaxis': 'y3'},
- {'line': {'color': '#007F00', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [1.0, 2.0, 3.0, 4.0],
- 'xaxis': 'x4',
- 'y': [0.0, 0.0, 1.0, 1.0],
- 'yaxis': 'y4'},
- {'line': {'color': '#00BFBF', 'dash': 'solid', 'opacity': 1, 'width': 1.0},
- 'mode': 'lines',
- 'x': [1.0, 2.0, 3.0, 4.0],
- 'xaxis': 'x5',
- 'y': [1.0, 0.0, 0.0, 1.0],
- 'yaxis': 'y5'}],
- 'layout': {'height': 480,
- 'showlegend': False,
- 'title': '',
- 'width': 640,
- 'xaxis': {'anchor': 'y',
- 'domain': [0.125, 0.90000000000000013],
- 'range': (1.0, 5.0),
- 'showgrid': False,
- 'title': ''},
- 'xaxis2': {'anchor': 'y2',
- 'domain': [0.125, 0.62647058823529411],
- 'range': (1.0, 4.0),
- 'showgrid': False,
- 'title': ''},
- 'xaxis3': {'anchor': 'y3',
- 'domain': [0.67205882352941182, 0.90000000000000013],
- 'range': (1.0, 4.0),
- 'showgrid': False,
- 'title': ''},
- 'xaxis4': {'anchor': 'y4',
- 'domain': [0.125, 0.35294117647058826],
- 'range': (1.0, 4.0),
- 'showgrid': False,
- 'title': ''},
- 'xaxis5': {'anchor': 'y5',
- 'domain': [0.39852941176470591, 0.62647058823529411],
- 'range': (1.0, 4.0),
- 'showgrid': False,
- 'title': ''},
- 'yaxis': {'anchor': 'x',
- 'domain': [0.66470588235294115, 0.90000000000000002],
- 'range': (5.0, 10.0),
- 'showgrid': False,
- 'title': ''},
- 'yaxis2': {'anchor': 'x2',
- 'domain': [0.38235294117647056, 0.61764705882352944],
- 'range': (0.0, 16.0),
- 'showgrid': False,
- 'title': ''},
- 'yaxis3': {'anchor': 'x3',
- 'domain': [0.099999999999999867, 0.61764705882352944],
- 'range': (0.0, 1000.0),
- 'showgrid': False,
- 'title': ''},
- 'yaxis4': {'anchor': 'x4',
- 'domain': [0.099999999999999867, 0.33529411764705874],
- 'range': (0.0, 1.0),
- 'showgrid': False,
- 'title': ''},
- 'yaxis5': {'anchor': 'x5',
- 'domain': [0.099999999999999867, 0.33529411764705874],
- 'range': (0.0, 1.0),
- 'showgrid': False,
- 'title': ''}}}
\ No newline at end of file
diff --git a/notebooks/PlotlyTest.ipynb b/notebooks/PlotlyTest.ipynb
deleted file mode 100644
index 030bc09..0000000
--- a/notebooks/PlotlyTest.ipynb
+++ /dev/null
@@ -1,222 +0,0 @@
-{
- "metadata": {
- "name": ""
- },
- "nbformat": 3,
- "nbformat_minor": 0,
- "worksheets": [
- {
- "cells": [
- {
- "cell_type": "heading",
- "level": 1,
- "metadata": {},
- "source": [
- "Plotly, matplotlib, and mplexporter."
- ]
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "Let's start by calling the IPython 'magic' function for matplotlib so that plots show up inline. The only import necessary to use plotly is the fig_to_plotly function."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "%matplotlib inline\n",
- "import matplotlib.pyplot as plt\n",
- "import matplotlib.gridspec as gridspec\n",
- "import numpy as np\n",
- "from mplexporter.renderers import fig_to_plotly"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 1
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "You can use the IPython.Demo username for now, or switch this for your own Plotly username and api_key. Don't have a username? You might try finding one at: https://plot.ly/"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "username = 'IPython.Demo'\n",
- "api_key = '1fw3zw2o13'"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 2
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "Here we instantiate a matplotlib figure object and fill it with stuff we want to plot! IPython's matplotlib magic function will pop it inline after you run the code block."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fig1 = plt.figure()\n",
- "x = np.arange(0,1.0,0.01)\n",
- "y1 = np.sin(2*np.pi*x)\n",
- "y2 = np.cos(4*np.pi*x)\n",
- "ax = fig1.add_subplot(111)\n",
- "ax.plot(x, y1, 'b--', label='sin')\n",
- "ax.plot(x, y2, 'ro', label='cos')\n",
- "ax.set_title(\"It's a Sign\")\n",
- "ax.set_xlabel('time')\n",
- "ax.set_ylabel('amplitude')"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 3,
- "text": [
- "<matplotlib.text.Text at 0x11218d890>"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAY0AAAEZCAYAAABrUHmEAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XtcFdXaB/DfRvCOgKiEwAndeBRFETMVfRW0EEQlu6m9\nnaOmmaV5qc57NNC8lL6a1ZuXjpnlpZOV5fHKxcwS9KSItyNeUUgNUFATRVFDYb1/DCCXvdnD3nNZ\nM/N8P5/94bJnzzyz1mIWM7PWMybGGAMhhBAigpPaARBCCNEO6jQIIYSIRp0GIYQQ0ajTIIQQIhp1\nGoQQQkSjToMQQoho1GkQwpG9e/eiQ4cOaodBiFXUaRBD8ff3x88//wwAWLt2Lfr27Vvl/TFjxmDd\nunWyxnDy5EkMHDgQnp6e8PDwQPfu3ZGUlAQA6Nu3L86cOSPr9glxhLPaARCiJJPJ5ND7Uhg6dCgm\nTZqExMREM [...]
- "text": [
- "<matplotlib.figure.Figure at 0x112184bd0>"
- ]
- }
- ],
- "prompt_number": 3
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "Like keeping your data around? Want to share your plots and/or data online? The following line takes the matplotlib figure object, extracts the data with mplexporter, renders a new plot with PlotlyRenderer, and sends it to Plotly. The plot shows up inline because of the 'notebook=True' keyword argument. This causes the fig_to_plotly function to call 'plotly.iplot' (IPython plot) instead of the normal 'plotly.plot' function. Taking that keyword argument out defaults to the normal p [...]
- "\n",
- "Note how you can zoom, pan, autoscale, and see data points by hovering. The data you plotted is right there. If you want to change the style, layout, etc. on plotly, you can click the link below the plot."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fig_to_plotly(fig1, username, api_key, notebook=True)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "html": [
- "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/1263/600/450\" width=\"650\"></iframe>"
- ],
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 4,
- "text": [
- "<IPython.core.display.HTML at 0x11217dfd0>"
- ]
- }
- ],
- "prompt_number": 4
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "But why have one axes object when you could have five!? Gridspec is a handy way to partition figure space into nice looking subplots. Here are just some simple line plots stretching over a 3x3 grid of plotting areas."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fig2 = plt.figure() # matplotlib.figure.Figure obj\n",
- "gs = gridspec.GridSpec(3, 3)\n",
- "ax1 = fig2.add_subplot(gs[0,:])\n",
- "ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')\n",
- "ax2 = fig2.add_subplot(gs[1,:-1])\n",
- "ax2.plot([1,2,3,4], [1,4,9,16], 'k-')\n",
- "ax3 = fig2.add_subplot(gs[1:, 2])\n",
- "ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')\n",
- "ax4 = fig2.add_subplot(gs[2,0])\n",
- "ax4.plot([1,2,3,4], [0,0,1,1], 'g-')\n",
- "ax5 = fig2.add_subplot(gs[2,1])\n",
- "ax5.plot([1,2,3,4], [1,0,0,1], 'c-')\n",
- "gs.update(wspace=0.5, hspace=0.5)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAEACAYAAABI5zaHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXtc1HX2/18odFELQwUSMJT7iMKYSda6oYgmBrnrpTCV\n1KzN3bx8d7fMfbRqv0L6umVaq13WXLQU+1qrZkppcVuFMEWzSEGFBARK0BTRQOb8/phm5DL3ec9n\nPp+Z83w8eMDMfD7v9+Gc+Zw5cz7nvN8eRERgGIZhXIpuzhaAYRiGEQ87d4ZhGBeEnTvDMIwLws6d\nYRjGBWHnzjAM44Kwc2cYhnFBrHLuc+bMgZ+fH4YMGaJ/rrGxEYmJiQgPD8e4ceNw8eJF4UIyDMMw\n1mGVc589ezays7M7PJeRkYHExESUlZUhISEBGRkZQgVkGIZhrMfD2iamyspKJCcn4/jx4wCAyMhI\n5OXlwc/PD [...]
- "text": [
- "<matplotlib.figure.Figure at 0x1121e5d50>"
- ]
- }
- ],
- "prompt_number": 5
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "Again, a simple line of code sends the above figure to Plotly and it responds by sticking back into this notebook."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fig_to_plotly(fig2, username=username, api_key=api_key, notebook=True)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "html": [
- "<iframe height=\"500\" id=\"igraph\" scrolling=\"no\" seamless=\"seamless\" src=\"https://plot.ly/~IPython.Demo/1264/600/450\" width=\"650\"></iframe>"
- ],
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 6,
- "text": [
- "<IPython.core.display.HTML at 0x1121e4310>"
- ]
- }
- ],
- "prompt_number": 6
- },
- {
- "cell_type": "heading",
- "level": 4,
- "metadata": {},
- "source": [
- "Follow and/or contribute to the mplexporter progress at: https://github.com/mpld3/mplexporter"
- ]
- }
- ],
- "metadata": {}
- }
- ]
-}
\ 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