Show Sidebar Hide Sidebar

IPython Notebook Widgets in Python

How to make IPython Notebook Widgets in Python with Plotly.

In [1]:
import plotly.plotly as py
from plotly.graph_objs import *
from IPython.display import Image
In [2]:
from plotly.widgets import GraphWidget
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/html.py:14: ShimWarning:

The `IPython.html` package has been deprecated. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/utils/traitlets.py:5: UserWarning:

IPython.utils.traitlets has moved to a top-level traitlets package.

In [3]:
help(GraphWidget)
Help on class GraphWidget in module plotly.widgets.graph_widget:

class GraphWidget(ipywidgets.widgets.widget.DOMWidget)
 |  An interactive Plotly graph widget for use in IPython
 |  Notebooks.
 |  
 |  Method resolution order:
 |      GraphWidget
 |      ipywidgets.widgets.widget.DOMWidget
 |      ipywidgets.widgets.widget.Widget
 |      traitlets.config.configurable.LoggingConfigurable
 |      traitlets.config.configurable.Configurable
 |      traitlets.traitlets.HasTraits
 |      traitlets.traitlets._NewBase
 |      traitlets.traitlets.HasDescriptors
 |      traitlets.traitlets._NewBase
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, graph_url='https://plot.ly/~playground/7', **kwargs)
 |      Initialize a plotly graph widget
 |      
 |      Args:
 |          graph_url: The url of a Plotly graph
 |      
 |      Example:
 |          ```
 |          GraphWidget('https://plot.ly/~chris/3375')
 |          ```
 |  
 |  add_traces(self, traces, new_indices=None)
 |      Add new data traces to a graph.
 |      
 |      If `new_indices` isn't specified, they are simply appended.
 |      
 |      Args:
 |          traces (dict or list of dicts, or class of plotly.graph_objs):trace
 |          new_indices (list[int]|None), optional: The final indices the
 |              added traces should occupy in the graph.
 |      
 |      Examples:
 |          Initialization - Start each example below with this setup:
 |          ```
 |          from plotly.widgets import GraphWidget
 |          from plotly.graph_objs import Scatter
 |          from IPython.display import display
 |      
 |          graph = GraphWidget('https://plot.ly/~chris/3979')
 |          display(graph)
 |          ```
 |      
 |          Example 1 - Add a scatter/line trace to the graph
 |          ```
 |          graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 4, 5]))
 |          ```
 |      
 |          Example 2 - Add a scatter trace and set it to to be the
 |                      second trace. This will appear as the second
 |                      item in the legend.
 |          ```
 |          graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 6, 5]),
 |                           new_indices=[1])
 |          ```
 |      
 |          Example 3 - Add multiple traces to the graph
 |          ```
 |          graph.add_traces([
 |              Scatter(x = [1, 2, 3], y = [5, 6, 5]),
 |              Scatter(x = [1, 2.5, 3], y = [5, 8, 5])
 |          ])
 |          ```
 |  
 |  delete_traces(self, indices)
 |      Delete data traces from a graph.
 |      
 |      Args:
 |          indices (list[int]): The indices of the traces to be removed
 |      
 |      Example - Delete the 2nd trace:
 |          ```
 |          from plotly.widgets import GraphWidget
 |          from IPython.display import display
 |      
 |          graph = GraphWidget('https://plot.ly/~chris/3979')
 |          display(graph)
 |      
 |      
 |          graph.delete_traces([1])
 |          ```
 |  
 |  extend_traces(self, update, indices=(0,), max_points=None)
 |      Append data points to existing traces in the Plotly graph.
 |      
 |      Args:
 |          update (dict):
 |              dict where keys are the graph attribute strings
 |              and values are arrays of arrays with values to extend.
 |      
 |              Each array in the array will extend a trace.
 |      
 |              Valid keys include:
 |                  'x', 'y', 'text,
 |                  'marker.color', 'marker.size', 'marker.symbol',
 |                  'marker.line.color', 'marker.line.width'
 |      
 |          indices (list, int):
 |              Specify which traces to apply the `update` dict to.
 |              If indices are not given, the update will apply to
 |              the traces in order.
 |      
 |          max_points (int or dict, optional):
 |              If specified, then only show the `max_points` most
 |              recent points in the graph.
 |              This is useful to prevent traces from becoming too
 |              large (and slow) or for creating "windowed" graphs
 |              in monitoring applications.
 |      
 |              To set max_points to different values for each trace
 |              or attribute, set max_points to a dict mapping keys
 |              to max_points values. See the examples below.
 |      
 |          Examples:
 |              Initialization - Start each example below with this setup:
 |              ```
 |              from plotly.widgets import GraphWidget
 |              from IPython.display import display
 |      
 |              graph = GraphWidget()
 |              graph.plot([
 |                  {'x': [], 'y': []},
 |                  {'x': [], 'y': []}
 |              ])
 |      
 |              display(graph)
 |              ```
 |      
 |              Example 1 - Extend the first trace with x and y data
 |              ```
 |              graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},
 |                                  indices=[0])
 |              ```
 |      
 |              Example 2 - Extend the second trace with x and y data
 |              ```
 |              graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},
 |                                  indices=[1])
 |              ```
 |      
 |              Example 3 - Extend the first two traces with x and y data
 |              ```
 |              graph.extend_traces({
 |                  'x': [[1, 2, 3], [2, 3, 4]],
 |                  'y': [[10, 20, 30], [3, 4, 3]]
 |              }, indices=[0, 1])
 |              ```
 |      
 |              Example 4 - Extend the first trace with x and y data and
 |                          limit the length of data in that trace to 50
 |                          points.
 |              ```
 |      
 |              graph.extend_traces({
 |                  'x': [range(100)],
 |                  'y': [range(100)]
 |              }, indices=[0, 1], max_points=50)
 |              ```
 |      
 |              Example 5 - Extend the first and second trace with x and y data
 |                          and limit the length of data in the first trace to
 |                          25 points and the second trace to 50 points.
 |              ```
 |              new_points = range(100)
 |              graph.extend_traces({
 |                      'x': [new_points, new_points],
 |                      'y': [new_points, new_points]
 |                  },
 |                  indices=[0, 1],
 |                  max_points={
 |                      'x': [25, 50],
 |                      'y': [25, 50]
 |                  }
 |              )
 |              ```
 |      
 |              Example 6 - Update other attributes, like marker colors and
 |                          sizes and text
 |              ```
 |              # Initialize a plot with some empty attributes
 |              graph.plot([{
 |                  'x': [],
 |                  'y': [],
 |                  'text': [],
 |                  'marker': {
 |                      'size': [],
 |                      'color': []
 |                  }
 |              }])
 |              # Append some data into those attributes
 |              graph.extend_traces({
 |                  'x': [[1, 2, 3]],
 |                  'y': [[10, 20, 30]],
 |                  'text': [['A', 'B', 'C']],
 |                  'marker.size': [[10, 15, 20]],
 |                  'marker.color': [['blue', 'red', 'orange']]
 |              }, indices=[0])
 |              ```
 |      
 |              Example 7 - Live-update a graph over a few seconds
 |              ```
 |              import time
 |      
 |              graph.plot([{'x': [], 'y': []}])
 |              for i in range(10):
 |                  graph.extend_traces({
 |                      'x': [[i]],
 |                      'y': [[i]]
 |                  }, indices=[0])
 |      
 |                  time.sleep(0.5)
 |              ```
 |  
 |  hover(self, *hover_objs)
 |      Show hover labels over the points specified in hover_obj.
 |      
 |      Hover labels are the labels that normally appear when the
 |      mouse hovers over points in the plotly graph.
 |      
 |      Args:
 |          hover_objs (tuple of dicts):
 |              Specifies which points to place hover labels over.
 |      
 |              The location of the hover labels is described by a dict with
 |              keys and'xval' and/or 'yval' or 'curveNumber' and 'pointNumber'
 |              and optional keys 'hovermode' and 'subplot'
 |      
 |              'xval' and 'yval' specify the (x, y) coordinates to
 |              place the label.
 |              'xval' and 'yval need to be close to a point drawn in a graph.
 |      
 |              'curveNumber' and 'pointNumber' specify the trace number and
 |              the index theof the point in that trace respectively.
 |      
 |              'subplot' describes which axes to the coordinates refer to.
 |              By default, it is equal to 'xy'. For example, to specify the
 |              second x-axis and the third y-axis, set 'subplot' to 'x2y3'
 |      
 |              'hovermode' is either 'closest', 'x', or 'y'.
 |              When set to 'x', all data sharing the same 'x' coordinate will
 |              be shown on screen with corresponding trace labels.
 |              When set to 'y' all data sharing the same 'y' coordinates will
 |              be shown on the screen with corresponding trace labels.
 |              When set to 'closest', information about the data point closest
 |              to where the viewer is hovering will appear.
 |      
 |              Note: If 'hovermode' is 'x', only 'xval' needs to be set.
 |                    If 'hovermode' is 'y', only 'yval' needs to be set.
 |                    If 'hovermode' is 'closest', 'xval' and 'yval' both
 |                    need to be set.
 |      
 |              Note: 'hovermode' can be toggled by the user in the graph
 |                    toolbar.
 |      
 |              Note: It is not currently possible to apply multiple hover
 |                    labels to points on different axes.
 |      
 |              Note: `hover` can only be called with multiple dicts if
 |                    'curveNumber' and 'pointNumber' are the keys of the dicts
 |      
 |      Examples:
 |          Initialization - Start each example below with this setup:
 |          ```
 |          from plotly.widgets import GraphWidget
 |          from IPython.display import display
 |      
 |          graph = GraphWidget('https://plot.ly/~chris/3979')
 |          display(graph)
 |          ```
 |      
 |          Example 1 - Apply a label to the (x, y) point (3, 2)
 |          ```
 |          graph.hover({'xval': 3, 'yval': 2, 'hovermode': 'closest'})
 |          ```
 |      
 |          Example 2 -Apply a labels to all the points with the x coordinate 3
 |          ```
 |          graph.hover({'xval': 3, 'hovermode': 'x'})
 |          ```
 |      
 |          Example 3 - Apply a label to the first point of the first trace
 |                      and the second point of the second trace.
 |          ```
 |          graph.hover({'curveNumber': 0, 'pointNumber': 0},
 |                      {'curveNumber': 1, 'pointNumber': 1})
 |          ```
 |  
 |  on_click(self, callback, remove=False)
 |      Assign a callback to click events propagated
 |      by clicking on point(s) in the Plotly graph.
 |      
 |      Args:
 |          callback (function): Callback function this is called
 |              on click events with the signature:
 |              callback(widget, hover_obj) -> None
 |      
 |              Args:
 |                  widget (GraphWidget): The current instance
 |                  of the graph widget that this callback is assigned to.
 |      
 |                  click_obj (dict): a nested dict that describes
 |                  which point(s) were clicked on.
 |      
 |                  click_obj example:
 |                  [
 |                      {
 |                          'curveNumber': 1,
 |                          'pointNumber': 2,
 |                          'x': 4,
 |                          'y': 14
 |                      }
 |                  ]
 |      
 |          remove (bool, optional): If False, attach the callback.
 |              If True, remove the callback. Defaults to False.
 |      
 |      
 |      Returns:
 |          None
 |      
 |      Example:
 |      ```
 |      from IPython.display import display
 |      def message_handler(widget, msg):
 |          display(widget._graph_url)
 |          display(msg)
 |      
 |      g = GraphWidget('https://plot.ly/~chris/3375')
 |      display(g)
 |      
 |      g.on_click(message_handler)
 |      ```
 |  
 |  on_hover(self, callback, remove=False)
 |      Assign a callback to hover events propagated
 |      by hovering over points in the Plotly graph.
 |      
 |      Args:
 |          callback (function): Callback function this is called
 |              on hover events with the signature:
 |              callback(widget, hover_obj) -> None
 |      
 |              Args:
 |                  widget (GraphWidget): The current instance
 |                  of the graph widget that this callback is assigned to.
 |      
 |                  hover_obj (dict): a nested dict that describes
 |                  which point(s) was hovered over.
 |      
 |                  hover_obj example:
 |                  [
 |                      {
 |                                  'curveNumber': 1,
 |                                  'pointNumber': 2,
 |                                  'x': 4,
 |                                  'y': 14
 |                      }
 |                  ]
 |      
 |          remove (bool, optional): If False, attach the callback.
 |              If True, remove the callback. Defaults to False.
 |      
 |      
 |      Returns:
 |          None
 |      
 |      Example:
 |      ```
 |      from IPython.display import display
 |      def message_handler(widget, hover_msg):
 |          display(widget._graph_url)
 |          display(hover_msg)
 |      
 |      g = GraphWidget('https://plot.ly/~chris/3375')
 |      display(g)
 |      
 |      g.on_hover(message_handler)
 |      ```
 |  
 |  on_zoom(self, callback, remove=False)
 |      Assign a callback to zoom events propagated
 |      by zooming in regions in the Plotly graph.
 |      
 |      Args:
 |          callback (function): Callback function this is called
 |              on zoom events with the signature:
 |              callback(widget, ranges) -> None
 |      
 |              Args:
 |                  widget (GraphWidget): The current instance
 |                  of the graph widget that this callback is assigned to.
 |      
 |                  ranges (dict): A description of the
 |                      region that was zoomed into.
 |      
 |                      ranges example:
 |                      {
 |                          'x': [1.8399058038561549, 2.16443359662],
 |                          'y': [4.640902872777017, 7.855677154582]
 |                      }
 |      
 |                  remove (bool, optional): If False, attach the callback.
 |                      If True, remove the callback. Defaults to False.
 |      
 |      Returns:
 |          None
 |      
 |      Example:
 |      ```
 |      from IPython.display import display
 |      def message_handler(widget, ranges):
 |          display(widget._graph_url)
 |          display(ranges)
 |      
 |      g = GraphWidget('https://plot.ly/~chris/3375')
 |      display(g)
 |      
 |      g.on_zoom(message_handler)
 |      ```
 |  
 |  plot(self, figure_or_data, validate=True)
 |      Plot figure_or_data in the Plotly graph widget.
 |      
 |      Args:
 |          figure_or_data (dict, list, or plotly.graph_obj object):
 |              The standard Plotly graph object that describes Plotly
 |              graphs as used in `plotly.plotly.plot`. See examples
 |              of the figure_or_data in https://plot.ly/python/
 |      
 |      Returns: None
 |      
 |      Example 1 - Graph a scatter plot:
 |      ```
 |      from plotly.graph_objs import Scatter
 |      g = GraphWidget()
 |      g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])
 |      ```
 |      
 |      Example 2 - Graph a scatter plot with a title:
 |      ```
 |      from plotly.graph_objs import Scatter, Figure, Data
 |      fig = Figure(
 |          data = Data([
 |              Scatter(x=[1, 2, 3], y=[20, 15, 13])
 |          ]),
 |          layout = Layout(title='Experimental Data')
 |      )
 |      
 |      g = GraphWidget()
 |      g.plot(fig)
 |      ```
 |      
 |      Example 3 - Clear a graph widget
 |      ```
 |      from plotly.graph_objs import Scatter, Figure
 |      g = GraphWidget()
 |      g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])
 |      
 |      # Now clear it
 |      g.plot({}) # alternatively, g.plot(Figure())
 |      ```
 |  
 |  relayout(self, layout)
 |      Update the layout of the Plotly graph.
 |      
 |      Args:
 |          layout (dict):
 |              dict where keys are the graph attribute strings
 |              and values are the value of the graph attribute.
 |      
 |              To update graph objects that are nested, like
 |              the title of an axis, combine the keys with a period
 |              e.g. `xaxis.title`. To set a value of an element in an array,
 |              like an axis's range, use brackets, e.g. 'xaxis.range[0]'.
 |              To replace an entire nested object, just specify the value to
 |              the sub-object. See example 4 below.
 |      
 |              See all of the layout attributes in our reference documentation
 |              https://plot.ly/python/reference/#Layout
 |              Or by calling `help` on `plotly.graph_objs.Layout`
 |      
 |      Examples - Start each example below with this setup:
 |          Initialization:
 |          ```
 |          from plotly.widgets import GraphWidget
 |          from IPython.display import display
 |      
 |          graph = GraphWidget('https://plot.ly/~chris/3979')
 |          display(graph)
 |          ```
 |      
 |          Example 1 - Update the title
 |          ```
 |          graph.relayout({'title': 'Experimental results'})
 |          ```
 |      
 |          Example 2 - Update the xaxis range
 |          ```
 |          graph.relayout({'xaxis.range': [-1, 6]})
 |          ```
 |      
 |          Example 3 - Update the first element of the xaxis range
 |          ```
 |          graph.relayout({'xaxis.range[0]': -3})
 |          ```
 |      
 |          Example 4 - Replace the entire xaxis object
 |          ```
 |          graph.relayout({'xaxis': {'title': 'Experimental results'}})
 |          ```
 |  
 |  reorder_traces(self, current_indices, new_indices=None)
 |      Reorder the traces in a graph.
 |      
 |      The order of the traces determines the order of the legend entries
 |      and the layering of the objects drawn in the graph, i.e. the first
 |      trace is drawn first and the second trace is drawn on top of the
 |      first trace.
 |      
 |      Args:
 |          current_indices (list[int]): The index of the traces to reorder.
 |      
 |          new_indices (list[int], optional): The index of the traces
 |              specified by `current_indices` after ordering.
 |              If None, then move the traces to the end.
 |      
 |      Examples:
 |          Example 1 - Move the first trace to the second to last
 |              position, the second trace to the last position
 |          ```
 |          graph.move_traces([0, 1])
 |          ```
 |      
 |          Example 2 - Move the first trace to the second position,
 |              the second trace to the first position.
 |          ```
 |          graph.move_traces([0], [1])
 |          ```
 |  
 |  restyle(self, update, indices=None)
 |      Update the style of existing traces in the Plotly graph.
 |      
 |      Args:
 |          update (dict):
 |              dict where keys are the graph attribute strings
 |              and values are the value of the graph attribute.
 |      
 |              To update graph objects that are nested, like
 |              a marker's color, combine the keys with a period,
 |              e.g. `marker.color`. To replace an entire nested object,
 |              like `marker`, set the value to the object.
 |              See Example 2 below.
 |      
 |              To update an attribute of multiple traces, set the
 |              value to an list of values. If the list is shorter
 |              than the number of traces, the values will wrap around.
 |              Note: this means that for values that are naturally an array,
 |              like `x` or `colorscale`, you need to wrap the value
 |              in an extra array,
 |              i.e. {'colorscale': [[[0, 'red'], [1, 'green']]]}
 |      
 |              You can also supply values to different traces with the
 |              indices argument.
 |      
 |              See all of the graph attributes in our reference documentation
 |              here: https://plot.ly/python/reference or by calling `help` on
 |              graph objects in `plotly.graph_objs`.
 |      
 |          indices (list, optional):
 |              Specify which traces to apply the update dict to.
 |              Negative indices are supported.
 |              If indices are not given, the update will apply to
 |              *all* traces.
 |      
 |      Examples:
 |          Initialization - Start each example below with this setup:
 |          ```
 |          from plotly.widgets import GraphWidget
 |          from IPython.display import display
 |      
 |          graph = GraphWidget()
 |          display(graph)
 |          ```
 |      
 |          Example 1 - Set `marker.color` to red in every trace in the graph
 |          ```
 |          graph.restyle({'marker.color': 'red'})
 |          ```
 |      
 |          Example 2 - Replace `marker` with {'color': 'red'}
 |          ```
 |          graph.restyle({'marker': {'color': red'}})
 |          ```
 |      
 |          Example 3 - Set `marker.color` to red
 |                      in the first trace of the graph
 |          ```
 |          graph.restyle({'marker.color': 'red'}, indices=[0])
 |          ```
 |      
 |          Example 4 - Set `marker.color` of all of the traces to
 |              alternating sequences of red and green
 |          ```
 |          graph.restyle({'marker.color': ['red', 'green']})
 |          ```
 |      
 |          Example 5 - Set just `marker.color` of the first two traces
 |                      to red and green
 |          ```
 |          graph.restyle({'marker.color': ['red', 'green']}, indices=[0, 1])
 |          ```
 |      
 |          Example 6 - Set multiple attributes of all of the traces
 |          ```
 |          graph.restyle({
 |              'marker.color': 'red',
 |              'line.color': 'green'
 |          })
 |          ```
 |      
 |          Example 7 - Update the data of the first trace
 |          ```
 |          graph.restyle({
 |              'x': [[1, 2, 3]],
 |              'y': [[10, 20, 30]],
 |          }, indices=[0])
 |          ```
 |      
 |          Example 8 - Update the data of the first two traces
 |          ```
 |          graph.restyle({
 |              'x': [[1, 2, 3],
 |                    [1, 2, 4]],
 |              'y': [[10, 20, 30],
 |                    [5, 8, 14]],
 |          }, indices=[0, 1])
 |          ```
 |  
 |  save(self, ignore_defaults=False, filename='')
 |      Save a copy of the current state of the widget in plotly.
 |      
 |      :param (bool) ignore_defaults: Auto-fill in unspecified figure keys?
 |      :param (str) filename: Name of the file on plotly.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  url
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from ipywidgets.widgets.widget.DOMWidget:
 |  
 |  background_color
 |      A string holding a valid HTML color such as 'blue', '#060482', '#A80'
 |  
 |  border_color
 |      A string holding a valid HTML color such as 'blue', '#060482', '#A80'
 |  
 |  border_radius
 |      A casting version of the unicode trait.
 |  
 |  border_style
 |      An enum of strings where the case should be ignored.
 |  
 |  border_width
 |      A casting version of the unicode trait.
 |  
 |  color
 |      A string holding a valid HTML color such as 'blue', '#060482', '#A80'
 |  
 |  font_family
 |      A trait for unicode strings.
 |  
 |  font_size
 |      A casting version of the unicode trait.
 |  
 |  font_style
 |      An enum of strings where the case should be ignored.
 |  
 |  font_weight
 |      An enum of strings where the case should be ignored.
 |  
 |  height
 |      A casting version of the unicode trait.
 |  
 |  margin
 |      A casting version of the unicode trait.
 |  
 |  padding
 |      A casting version of the unicode trait.
 |  
 |  visible
 |      A boolean (True, False) trait.
 |  
 |  width
 |      A casting version of the unicode trait.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from ipywidgets.widgets.widget.Widget:
 |  
 |  __del__(self)
 |      Object disposal
 |  
 |  add_traits(self, **traits)
 |      Dynamically add trait attributes to the Widget.
 |  
 |  close(self)
 |      Close method.
 |      
 |      Closes the underlying comm.
 |      When the comm is closed, all of the widget views are automatically
 |      removed from the front-end.
 |  
 |  get_state(self, key=None)
 |      Gets the widget state, or a piece of it.
 |      
 |      Parameters
 |      ----------
 |      key : unicode or iterable (optional)
 |          A single property's name or iterable of property names to get.
 |      
 |      Returns
 |      -------
 |      state : dict of states
 |      metadata : dict
 |          metadata for each field: {key: metadata}
 |  
 |  hold_sync(*args, **kwds)
 |      Hold syncing any state until the outermost context manager exits
 |  
 |  on_displayed(self, callback, remove=False)
 |      (Un)Register a widget displayed callback.
 |      
 |      Parameters
 |      ----------
 |      callback: method handler
 |          Must have a signature of::
 |      
 |              callback(widget, **kwargs)
 |      
 |          kwargs from display are passed through without modification.
 |      remove: bool
 |          True if the callback should be unregistered.
 |  
 |  on_msg(self, callback, remove=False)
 |      (Un)Register a custom msg receive callback.
 |      
 |      Parameters
 |      ----------
 |      callback: callable
 |          callback will be passed three arguments when a message arrives::
 |      
 |              callback(widget, content, buffers)
 |      
 |      remove: bool
 |          True if the callback should be unregistered.
 |  
 |  open(self)
 |      Open a comm to the frontend if one isn't already open.
 |  
 |  send(self, content, buffers=None)
 |      Sends a custom msg to the widget model in the front-end.
 |      
 |      Parameters
 |      ----------
 |      content : dict
 |          Content of the message to send.
 |      buffers : list of binary buffers
 |          Binary buffers to send with message
 |  
 |  send_state(self, key=None)
 |      Sends the widget state, or a piece of it, to the front-end.
 |      
 |      Parameters
 |      ----------
 |      key : unicode, or iterable (optional)
 |          A single property's name or iterable of property names to sync with the front-end.
 |  
 |  set_state(self, sync_data)
 |      Called when a state is received from the front-end.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from ipywidgets.widgets.widget.Widget:
 |  
 |  handle_comm_opened(comm, msg)
 |      Static method, called when a widget is constructed.
 |  
 |  on_widget_constructed(callback)
 |      Registers a callback to be called when a widget is constructed.
 |      
 |      The callback must have the following signature:
 |      callback(widget)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from ipywidgets.widgets.widget.Widget:
 |  
 |  comm
 |      A trait whose value must be an instance of a specified class.
 |      
 |      The value can also be an instance of a subclass of the specified class.
 |      
 |      Subclasses can declare default classes by overriding the klass attribute
 |  
 |  keys
 |      An instance of a Python list.
 |  
 |  model_id
 |      Gets the model id of this widget.
 |      
 |      If a Comm doesn't exist yet, a Comm will be created automagically.
 |  
 |  msg_throttle
 |      An int trait.
 |  
 |  version
 |      An int trait.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from ipywidgets.widgets.widget.Widget:
 |  
 |  widget_types = {'IPython.Accordion': <class 'ipywidgets.widgets.widget...
 |  
 |  widgets = {}
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from traitlets.config.configurable.LoggingConfigurable:
 |  
 |  log
 |      A trait whose value must be an instance of a specified class.
 |      
 |      The value can also be an instance of a subclass of the specified class.
 |      
 |      Subclasses can declare default classes by overriding the klass attribute
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from traitlets.config.configurable.Configurable:
 |  
 |  update_config(self, config)
 |      Update config and trigger reload of config via trait events
 |  
 |  ----------------------------------------------------------------------
 |  Class methods inherited from traitlets.config.configurable.Configurable:
 |  
 |  class_config_rst_doc(cls) from traitlets.traitlets.MetaHasTraits
 |      Generate rST documentation for this class' config options.
 |      
 |      Excludes traits defined on parent classes.
 |  
 |  class_config_section(cls) from traitlets.traitlets.MetaHasTraits
 |      Get the config class config section
 |  
 |  class_get_help(cls, inst=None) from traitlets.traitlets.MetaHasTraits
 |      Get the help string for this class in ReST format.
 |      
 |      If `inst` is given, it's current trait values will be used in place of
 |      class defaults.
 |  
 |  class_get_trait_help(cls, trait, inst=None) from traitlets.traitlets.MetaHasTraits
 |      Get the help string for a single trait.
 |      
 |      If `inst` is given, it's current trait values will be used in place of
 |      the class default.
 |  
 |  class_print_help(cls, inst=None) from traitlets.traitlets.MetaHasTraits
 |      Get the help string for a single trait and print it.
 |  
 |  section_names(cls) from traitlets.traitlets.MetaHasTraits
 |      return section names as a list
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from traitlets.config.configurable.Configurable:
 |  
 |  config
 |      A trait whose value must be an instance of a specified class.
 |      
 |      The value can also be an instance of a subclass of the specified class.
 |      
 |      Subclasses can declare default classes by overriding the klass attribute
 |  
 |  parent
 |      A trait whose value must be an instance of a specified class.
 |      
 |      The value can also be an instance of a subclass of the specified class.
 |      
 |      Subclasses can declare default classes by overriding the klass attribute
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from traitlets.traitlets.HasTraits:
 |  
 |  __getstate__(self)
 |  
 |  __setstate__(self, state)
 |  
 |  has_trait(self, name)
 |      Returns True if the object has a trait with the specified name.
 |  
 |  hold_trait_notifications(*args, **kwds)
 |      Context manager for bundling trait change notifications and cross
 |      validation.
 |      
 |      Use this when doing multiple trait assignments (init, config), to avoid
 |      race conditions in trait notifiers requesting other trait values.
 |      All trait notifications will fire after all values have been assigned.
 |  
 |  notify_change(self, change)
 |  
 |  observe(self, handler, names=traitlets.All, type='change')
 |      Setup a handler to be called when a trait changes.
 |      
 |      This is used to setup dynamic notifications of trait changes.
 |      
 |      Parameters
 |      ----------
 |      handler : callable
 |          A callable that is called when a trait changes. Its
 |          signature can be ``handler()`` or ``handler(change)``, where change
 |          is a dictionary. The change dictionary at least holds a 'type' key.
 |          * ``type``: the type of notification.
 |          Other keys may be passed depending on the value of 'type'. In the
 |          case where type is 'change', we also have the following keys:
 |          * ``owner`` : the HasTraits instance
 |          * ``old`` : the old value of the modified trait attribute
 |          * ``new`` : the new value of the modified trait attribute
 |          * ``name`` : the name of the modified trait attribute.
 |      names : list, str, All
 |          If names is All, the handler will apply to all traits.  If a list
 |          of str, handler will apply to all names in the list.  If a
 |          str, the handler will apply just to that name.
 |      type : str, All (default: 'change')
 |          The type of notification to filter by. If equal to All, then all
 |          notifications are passed to the observe handler.
 |  
 |  on_trait_change(self, handler=None, name=None, remove=False)
 |      DEPRECATED: Setup a handler to be called when a trait changes.
 |      
 |      This is used to setup dynamic notifications of trait changes.
 |      
 |      Static handlers can be created by creating methods on a HasTraits
 |      subclass with the naming convention '_[traitname]_changed'.  Thus,
 |      to create static handler for the trait 'a', create the method
 |      _a_changed(self, name, old, new) (fewer arguments can be used, see
 |      below).
 |      
 |      If `remove` is True and `handler` is not specified, all change
 |      handlers for the specified name are uninstalled.
 |      
 |      Parameters
 |      ----------
 |      handler : callable, None
 |          A callable that is called when a trait changes.  Its
 |          signature can be handler(), handler(name), handler(name, new),
 |          handler(name, old, new), or handler(name, old, new, self).
 |      name : list, str, None
 |          If None, the handler will apply to all traits.  If a list
 |          of str, handler will apply to all names in the list.  If a
 |          str, the handler will apply just to that name.
 |      remove : bool
 |          If False (the default), then install the handler.  If True
 |          then unintall it.
 |  
 |  set_trait(self, name, value)
 |      Forcibly sets trait attribute, including read-only attributes.
 |  
 |  setup_instance(self)
 |  
 |  trait_metadata(self, traitname, key, default=None)
 |      Get metadata values for trait by key.
 |  
 |  trait_names(self, **metadata)
 |      Get a list of all the names of this class' traits.
 |  
 |  traits(self, **metadata)
 |      Get a ``dict`` of all the traits of this class.  The dictionary
 |      is keyed on the name and the values are the TraitType objects.
 |      
 |      The TraitTypes returned don't know anything about the values
 |      that the various HasTrait's instances are holding.
 |      
 |      The metadata kwargs allow functions to be passed in which
 |      filter traits based on metadata values.  The functions should
 |      take a single value as an argument and return a boolean.  If
 |      any function returns False, then the trait is not included in
 |      the output.  If a metadata key doesn't exist, None will be passed
 |      to the function.
 |  
 |  unobserve(self, handler, names=traitlets.All, type='change')
 |      Remove a trait change handler.
 |      
 |      This is used to unregister handlers to trait change notificiations.
 |      
 |      Parameters
 |      ----------
 |      handler : callable
 |          The callable called when a trait attribute changes.
 |      names : list, str, All (default: All)
 |          The names of the traits for which the specified handler should be
 |          uninstalled. If names is All, the specified handler is uninstalled
 |          from the list of notifiers corresponding to all changes.
 |      type : str or All (default: 'change')
 |          The type of notification to filter by. If All, the specified handler
 |          is uninstalled from the list of notifiers corresponding to all types.
 |  
 |  unobserve_all(self, name=traitlets.All)
 |      Remove trait change handlers of any type for the specified name.
 |      If name is not specified, removes all trait notifiers.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods inherited from traitlets.traitlets.HasTraits:
 |  
 |  class_own_traits(cls, **metadata) from traitlets.traitlets.MetaHasTraits
 |      Get a dict of all the traitlets defined on this class, not a parent.
 |      
 |      Works like `class_traits`, except for excluding traits from parents.
 |  
 |  class_trait_names(cls, **metadata) from traitlets.traitlets.MetaHasTraits
 |      Get a list of all the names of this class' traits.
 |      
 |      This method is just like the :meth:`trait_names` method,
 |      but is unbound.
 |  
 |  class_traits(cls, **metadata) from traitlets.traitlets.MetaHasTraits
 |      Get a ``dict`` of all the traits of this class.  The dictionary
 |      is keyed on the name and the values are the TraitType objects.
 |      
 |      This method is just like the :meth:`traits` method, but is unbound.
 |      
 |      The TraitTypes returned don't know anything about the values
 |      that the various HasTrait's instances are holding.
 |      
 |      The metadata kwargs allow functions to be passed in which
 |      filter traits based on metadata values.  The functions should
 |      take a single value as an argument and return a boolean.  If
 |      any function returns False, then the trait is not included in
 |      the output.  If a metadata key doesn't exist, None will be passed
 |      to the function.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from traitlets.traitlets.HasDescriptors:
 |  
 |  __new__(cls, *args, **kw)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from traitlets.traitlets._NewBase:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Initialize a Graph widget with a Plotly URL

In [4]:
url = py.plot({'data': [Scatter(x=[1, 2, 3], y=[4, 6, 9]), Scatter(x=[1, 2, 3], y=[10, 30, 20])]}, 
               filename = 'widget template', auto_open=False)
print url
https://plot.ly/~kevintest/512
In [5]:
graph = GraphWidget(url)
g = graph
graph
https://plot.ly/~kevintest/512
[{'curveNumber': 0, 'pointNumber': 2, 'x': 3, 'y': 9},
 {'curveNumber': 1, 'pointNumber': 2, 'x': 3, 'y': 20}]
In [6]:
# Which would render as the following
Image("https://cloud.githubusercontent.com/assets/12302455/15342229/9e54d8e2-1c61-11e6-95dc-9c87f1c1b24a.png")
Out[6]:

Update the Plotly graph. This is done entirely on the client

In [17]:
help(graph.restyle)
Help on method restyle in module plotly.widgets.graph_widget:

restyle(self, update, indices=None) method of plotly.widgets.graph_widget.GraphWidget instance
    Update the style of existing traces in the Plotly graph.
    
    Args:
        update (dict):
            dict where keys are the graph attribute strings
            and values are the value of the graph attribute.
    
            To update graph objects that are nested, like
            a marker's color, combine the keys with a period,
            e.g. `marker.color`. To replace an entire nested object,
            like `marker`, set the value to the object.
            See Example 2 below.
    
            To update an attribute of multiple traces, set the
            value to an list of values. If the list is shorter
            than the number of traces, the values will wrap around.
            Note: this means that for values that are naturally an array,
            like `x` or `colorscale`, you need to wrap the value
            in an extra array,
            i.e. {'colorscale': [[[0, 'red'], [1, 'green']]]}
    
            You can also supply values to different traces with the
            indices argument.
    
            See all of the graph attributes in our reference documentation
            here: https://plot.ly/python/reference or by calling `help` on
            graph objects in `plotly.graph_objs`.
    
        indices (list, optional):
            Specify which traces to apply the update dict to.
            Negative indices are supported.
            If indices are not given, the update will apply to
            *all* traces.
    
    Examples:
        Initialization - Start each example below with this setup:
        ```
        from plotly.widgets import GraphWidget
        from IPython.display import display
    
        graph = GraphWidget()
        display(graph)
        ```
    
        Example 1 - Set `marker.color` to red in every trace in the graph
        ```
        graph.restyle({'marker.color': 'red'})
        ```
    
        Example 2 - Replace `marker` with {'color': 'red'}
        ```
        graph.restyle({'marker': {'color': red'}})
        ```
    
        Example 3 - Set `marker.color` to red
                    in the first trace of the graph
        ```
        graph.restyle({'marker.color': 'red'}, indices=[0])
        ```
    
        Example 4 - Set `marker.color` of all of the traces to
            alternating sequences of red and green
        ```
        graph.restyle({'marker.color': ['red', 'green']})
        ```
    
        Example 5 - Set just `marker.color` of the first two traces
                    to red and green
        ```
        graph.restyle({'marker.color': ['red', 'green']}, indices=[0, 1])
        ```
    
        Example 6 - Set multiple attributes of all of the traces
        ```
        graph.restyle({
            'marker.color': 'red',
            'line.color': 'green'
        })
        ```
    
        Example 7 - Update the data of the first trace
        ```
        graph.restyle({
            'x': [[1, 2, 3]],
            'y': [[10, 20, 30]],
        }, indices=[0])
        ```
    
        Example 8 - Update the data of the first two traces
        ```
        graph.restyle({
            'x': [[1, 2, 3],
                  [1, 2, 4]],
            'y': [[10, 20, 30],
                  [5, 8, 14]],
        }, indices=[0, 1])
        ```

In [22]:
graph.restyle({'name': ['control', 'experiment']})
In [23]:
graph.relayout({'xaxis.title': 'samples'})
In [24]:
graph.add_traces(Scatter(x=[1,2,3], y=[5, 4, 5], name='another sample'))
In [25]:
Image('https://cloud.githubusercontent.com/assets/12302455/15342272/079e0a58-1c62-11e6-926c-a364af809c4a.png')
Out[25]:

Update the graph's data

In [28]:
g.restyle({'x': [[1,2,3], 
               [1, 2, 4]],
         'y': [6*[10,20,35]]
}, indices=[0, 1])
In [29]:
Image('https://cloud.githubusercontent.com/assets/12302455/15342288/2aff6aa0-1c62-11e6-8f05-7cd15a49d9fa.png')
Out[29]:

Assign handlers to 'click', 'hover', and 'zoom' events

In [7]:
from IPython.display import display, clear_output
def message_handler(widget, msg):
    clear_output()
    print widget._graph_url
    display(msg)

g.on_click(message_handler)
g.on_hover(message_handler)
g.on_zoom(message_handler)

Manual hover over points

In [ ]:
g.hover({'xval': 2, 'yval': 8})

Here is a sequence of graph edits

In [13]:
Image(url='http://i.imgur.com/69wyqjV.gif')
Out[13]:
In [ ]:
graph #display the graph again
In [ ]:
from IPython.html import widgets # Widget definitions
import json
import time

style_sequence = [
    # Clear graph
    {
        'data': {
            'x': [],
            'y': [],
            'marker.color': '',
            'marker.size': '',
            'marker.symbol': '',
            'line.color': '',
            'line.width': '',
            'name': ''
        },
        'layout': {
            'title': '',
            'showlegend': False,
            'legend.x': '',
            'legend.y': '',
            'legend.bgcolor': ''
        },
        'hover': {}
    },
    # Add data
    {
        'data': {
            'x': [[1,2,3],
                  [1, 2, 4]],
         'y': [[10,20,30],
               [5, 8, 14]]
        },
        'traces': [0, 1]
    },
    # Restyle markers
    {
        'data': {
            'marker.color': ['rgb(0, 67, 88)', 'rgb(31, 138, 112)'],
            'marker.size': 10,
            'marker.symbol': 'hexagon-open'
        },
        'traces': [0, 1]
    },
    # Restyle lines
    {
        'data': {
            'line.color': ['rgb(0, 67, 88)', 'rgb(31, 138, 112)'],
            'line.width': 3
        }
    },
    # Add title
    {
        'layout': {
            'title': 'Trials',
        }
    },
    # Add legend
    {
        'layout': {
            'showlegend': True,
        }
    },
    # Add legend names
    {
        'data': {
            'name': ['Control', 'Experiment']
        },
        'traces': [0, 1]
    },
    # Move legend
    {
        'layout': {
            'legend.x': 0.02,
            'legend.y': 1,
            'legend.bgcolor': 'rgba(255, 255, 255, 0.5)'
        }
    },
    {'hover': {'xval': 2, 'yval': 8}},
    {'hover': {'xval': 2, 'yval': 8, 'hovermode': 'closest'}},
    {'xval': 2, 'yval': 8, 'hovermode': 'x'},
    {'hover': [{'curveNumber': 0, 'pointNumber': 0}]},
    {'hover': [{'curveNumber': 0, 'pointNumber': 0},
     {'curveNumber': 0, 'pointNumber': 1}]},
    {'hover': [{'curveNumber': 0, 'pointNumber': 2},
     {'curveNumber': 1, 'pointNumber': 1}]},
    {'hover': [{'curveNumber': 0, 'xval': 1, 'yval': 10},
     {'curveNumber': 0, 'xval': 2, 'yval': 20},
     {'curveNumber': 0, 'xval': 3, 'yval': 30},
     {'curveNumber': 1, 'xval': 1, 'yval': 5},
     {'curveNumber': 1, 'xval': 2, 'yval': 8},
     {'curveNumber': 1, 'xval': 4, 'yval': 14}
    ]}
]

for s in style_sequence:
    if 'data' in s:
        if 'traces' in s:
            g.restyle(s['data'], indices=s['traces'])
        else:
            g.restyle(s['data'])
    if 'layout' in s:
        g.relayout(s['layout'])
    if 'hover' in s:
        g.hover(s['hover'])
    time.sleep(3)
In [ ]:
# CSS styling within IPython notebook - feel free to re-use
#from IPython.core.display import HTML
#import urllib2

#HTML(urllib2.urlopen('http://bit.ly/1Bf5Hft').read())
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.