{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### New to Plotly?\n", "Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n", "
You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).\n", "
We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using a Single Slider to Set the Range" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "scrolled": true }, "outputs": [ { "data": { "application/javascript": [ "window.genUID = function() {\n", " return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n", " var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);\n", " return v.toString(16);\n", " });\n", "};\n", "\n", "\n", "define('graphWidget', [\"@jupyter-widgets/base\"], function (widget) {\n", "\n", " var GraphView = widget.DOMWidgetView.extend({\n", " render: function(){\n", " var that = this;\n", "\n", " var graphId = window.genUID();\n", " var loadingId = 'loading-'+graphId;\n", "\n", "\n", " var _graph_url = that.model.get('_graph_url');\n", "\n", " // variable plotlyDomain in the case of enterprise\n", " var url_parts = _graph_url.split('/');\n", " var plotlyDomain = url_parts[0] + '//' + url_parts[2];\n", "\n", " if(!('plotlyDomains' in window)){\n", " window.plotlyDomains = {};\n", " }\n", " window.plotlyDomains[graphId] = plotlyDomain;\n", "\n", " // Place IFrame in output cell div `$el`\n", " that.$el.css('width', '100%');\n", " that.$graph = $([''].join(' '));\n", " that.$graph.appendTo(that.$el);\n", "\n", " that.$loading = $('
Initializing...
')\n", " .appendTo(that.$el);\n", "\n", " // for some reason the 'width' is being changed in IPython 3.0.0\n", " // for the containing `div` element. There's a flicker here, but\n", " // I was unable to fix it otherwise.\n", " setTimeout(function () {\n", " if (IPYTHON_VERSION === '3') {\n", " $('#' + graphId)[0].parentElement.style.width = '100%';\n", " }\n", " }, 500);\n", "\n", " // initialize communication with the iframe\n", " if(!('pingers' in window)){\n", " window.pingers = {};\n", " }\n", "\n", " window.pingers[graphId] = setInterval(function() {\n", " that.graphContentWindow = $('#'+graphId)[0].contentWindow;\n", " that.graphContentWindow.postMessage({task: 'ping'}, plotlyDomain);\n", " }, 200);\n", "\n", " // Assign a message listener to the 'message' events\n", " // from iframe's postMessage protocol.\n", " // Filter the messages by iframe src so that the right message\n", " // gets passed to the right widget\n", " if(!('messageListeners' in window)){\n", " window.messageListeners = {};\n", " }\n", "\n", " window.messageListeners[graphId] = function(e) {\n", " if(_graph_url.indexOf(e.origin)>-1) {\n", " var frame = document.getElementById(graphId);\n", "\n", " if(frame === null){\n", " // frame doesn't exist in the dom anymore, clean up it's old event listener\n", " window.removeEventListener('message', window.messageListeners[graphId]);\n", " clearInterval(window.pingers[graphId]);\n", " } else if(frame.contentWindow === e.source) {\n", " // TODO: Stop event propagation, so each frame doesn't listen and filter\n", " var frameContentWindow = $('#'+graphId)[0].contentWindow;\n", " var message = e.data;\n", "\n", " if('pong' in message && message.pong) {\n", " $('#loading-'+graphId).hide();\n", " clearInterval(window.pingers[graphId]);\n", " that.send({event: 'pong', graphId: graphId});\n", " } else if (message.type==='hover' ||\n", " message.type==='zoom' ||\n", " message.type==='click' ||\n", " message.type==='unhover') {\n", "\n", " // click and hover events contain all of the data in the traces,\n", " // which can be a very large object and may take a ton of time\n", " // to pass to the python backend. Strip out the data, and require\n", " // the user to call get_figure if they need trace information\n", " if(message.type !== 'zoom') {\n", " for(var i in message.points) {\n", " delete message.points[i].data;\n", " delete message.points[i].fullData;\n", " }\n", " }\n", " that.send({event: message.type, message: message, graphId: graphId});\n", " } else if (message.task === 'getAttributes') {\n", " that.send({event: 'getAttributes', response: message.response});\n", " }\n", " }\n", " }\n", " };\n", "\n", " window.removeEventListener('message', window.messageListeners[graphId]);\n", " window.addEventListener('message', window.messageListeners[graphId]);\n", "\n", " },\n", "\n", " update: function() {\n", " // Listen for messages from the graph widget in python\n", " var jmessage = this.model.get('_message');\n", " var message = JSON.parse(jmessage);\n", "\n", " // check for duplicate messages\n", " if(!('messageIds' in window)){\n", " window.messageIds = {};\n", " }\n", "\n", " if(!(message.uid in window.messageIds)){\n", " // message hasn't been received yet, do stuff\n", " window.messageIds[message.uid] = true;\n", "\n", " if (message.fadeTo) {\n", " this.fadeTo(message);\n", " } else {\n", " var plot = $('#' + message.graphId)[0].contentWindow;\n", " plot.postMessage(message, window.plotlyDomains[message.graphId]);\n", " }\n", " }\n", "\n", " return GraphView.__super__.update.apply(this);\n", " },\n", "\n", " /**\n", " * Wrapper for jquery's `fadeTo` function.\n", " *\n", " * @param message Contains the id we need to find the element.\n", " */\n", " fadeTo: function (message) {\n", " var plot = $('#' + message.graphId);\n", " plot.fadeTo(message.duration, message.opacity);\n", " }\n", " });\n", "\n", " // Register the GraphView with the widget manager.\n", " return {\n", " GraphView: GraphView\n", " }\n", "\n", "});\n", "\n", "//@ sourceURL=graphWidget.js\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "875470f31e414a03ba03ec0fd4efe1e5" } }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4c285778175247cd9db6ada4acf8bb48" } }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import plotly.plotly as py\n", "import ipywidgets as widgets\n", "\n", "from ipywidgets import interact, interactive, fixed\n", "from IPython.core.display import HTML\n", "from IPython.display import display, clear_output\n", "from plotly.widgets import GraphWidget\n", "\n", "\n", "styles = ''''''\n", "\n", "HTML(styles)\n", "\n", "#this widget will display our plotly chart\n", "graph = GraphWidget(\"https://plotly.com/~jordanpeterson/889\")\n", "fig = py.get_figure(\"https://plotly.com/~jordanpeterson/889\")\n", "\n", "#find the range of the slider.\n", "xmin, xmax = fig['layout']['xaxis']['range']\n", "\n", "# use the interact decorator to tie a widget to the listener function\n", "@interact(y=widgets.FloatRangeSlider(min=xmin, max=xmax, step=(xmax-xmin)/1000.0, continuous_update=False))\n", "def update_plot(y):\n", " graph.relayout({'xaxis.range[0]': y[0], 'xaxis.range[1]': y[1]})\n", " \n", "#display the app \n", "graph" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using Two Sliders to Set Range" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "379b7547b12b443699f3adc9bb9afecb" } }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "79201a4c5b444665aba3176684e54f27" } }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4d6b4443addf42b7aa330ce0822713ec" } }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import plotly.plotly as py\n", "import ipywidgets as widgets\n", "\n", "from ipywidgets import interact, interactive, fixed\n", "from IPython.core.display import HTML\n", "from IPython.display import display, clear_output\n", "from plotly.widgets import GraphWidget\n", "from traitlets import link\n", "\n", "\n", "styles = ''''''\n", "\n", "HTML(styles)\n", "\n", "#this widget will display our plotly chart\n", "graph = GraphWidget(\"https://plotly.com/~jordanpeterson/889\")\n", "fig = py.get_figure(\"https://plotly.com/~jordanpeterson/889\")\n", "\n", "#find the range of the slider.\n", "xmin, xmax = fig['layout']['xaxis']['range']\n", "\n", "# let's define our listener functions that will respond to changes in the sliders\n", "def on_value_change_left(change):\n", " graph.relayout({'xaxis.range[0]': change['new']})\n", " \n", "def on_value_change_right(change):\n", " graph.relayout({'xaxis.range[1]': change['new']})\n", " \n", "# define the sliders\n", "left_slider = widgets.FloatSlider(min=xmin, max=xmax, value=xmin, description=\"Left Slider\")\n", "right_slider = widgets.FloatSlider(min=xmin, max=xmax, value=xmax, description=\"Right Slider\")\n", "\n", "# put listeners on slider activity\n", "left_slider.observe(on_value_change_left, names='value')\n", "right_slider.observe(on_value_change_right, names='value')\n", "\n", "# set a relationship between the left and right slider\n", "link((left_slider, 'max'), (right_slider, 'value'))\n", "link((left_slider, 'value'), (right_slider, 'min'))\n", "\n", "# display our app\n", "display(left_slider)\n", "display(right_slider)\n", "display(graph)\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sliders with 3d Plots" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "10921463ae5d42e6b544809cc744c6ae" } }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "3606c9d01d1d44528ede399a6ccd3e62" } }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import plotly.plotly as py\n", "import ipywidgets as widgets\n", "import numpy as np\n", "\n", "from ipywidgets import interact, interactive, fixed\n", "from IPython.core.display import HTML\n", "from IPython.display import display, clear_output\n", "from plotly.widgets import GraphWidget\n", "\n", "g = GraphWidget('https://plotly.com/~DemoAccount/10147/')\n", "x = y = np.arange(-5,5,0.1)\n", "yt = x[:,np.newaxis]\n", "\n", "# define our listener class\n", "class z_data:\n", " \n", " def __init__(self):\n", " self.z = np.cos(x*yt)+np.sin(x*yt)*2\n", " \n", " def on_z_change(self, name):\n", " new_value = name['new']\n", " \n", " self.z = np.cos(x*yt*(new_value+1)/100)+np.sin(x*yt*(new_value+1/100))\n", " self.replot()\n", " \n", " def replot(self):\n", " g.restyle({ 'z': [self.z], 'colorscale': 'Viridis'})\n", "\n", "# create sliders\n", "z_slider = widgets.FloatSlider(min=0,max=30,value=1,step=0.05, continuous_update=False)\n", "z_slider.description = 'Frequency'\n", "z_slider.value = 1\n", "\n", "# initialize listener class\n", "z_state = z_data()\n", "\n", "# activate listener on our slider\n", "z_slider.observe(z_state.on_z_change, 'value')\n", "\n", "# display our app\n", "display(z_slider)\n", "display(g)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Reference" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class GraphWidget in module plotly.widgets.graph_widget:\n", "\n", "class GraphWidget(ipywidgets.widgets.domwidget.DOMWidget)\n", " | An interactive Plotly graph widget for use in IPython\n", " | Notebooks.\n", " | \n", " | Method resolution order:\n", " | GraphWidget\n", " | ipywidgets.widgets.domwidget.DOMWidget\n", " | ipywidgets.widgets.widget.Widget\n", " | traitlets.config.configurable.LoggingConfigurable\n", " | traitlets.config.configurable.Configurable\n", " | traitlets.traitlets.HasTraits\n", " | traitlets.traitlets.HasDescriptors\n", " | __builtin__.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, graph_url='https://plotly.com/~playground/7', **kwargs)\n", " | Initialize a plotly graph widget\n", " | \n", " | Args:\n", " | graph_url: The url of a Plotly graph\n", " | \n", " | Example:\n", " | ```\n", " | GraphWidget('https://plotly.com/~chris/3375')\n", " | ```\n", " | \n", " | add_traces(self, traces, new_indices=None)\n", " | Add new data traces to a graph.\n", " | \n", " | If `new_indices` isn't specified, they are simply appended.\n", " | \n", " | Args:\n", " | traces (dict or list of dicts, or class of plotly.graph_objs):trace\n", " | new_indices (list[int]|None), optional: The final indices the\n", " | added traces should occupy in the graph.\n", " | \n", " | Examples:\n", " | Initialization - Start each example below with this setup:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from plotly.graph_objs import Scatter\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget('https://plotly.com/~chris/3979')\n", " | display(graph)\n", " | ```\n", " | \n", " | Example 1 - Add a scatter/line trace to the graph\n", " | ```\n", " | graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 4, 5]))\n", " | ```\n", " | \n", " | Example 2 - Add a scatter trace and set it to to be the\n", " | second trace. This will appear as the second\n", " | item in the legend.\n", " | ```\n", " | graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 6, 5]),\n", " | new_indices=[1])\n", " | ```\n", " | \n", " | Example 3 - Add multiple traces to the graph\n", " | ```\n", " | graph.add_traces([\n", " | Scatter(x = [1, 2, 3], y = [5, 6, 5]),\n", " | Scatter(x = [1, 2.5, 3], y = [5, 8, 5])\n", " | ])\n", " | ```\n", " | \n", " | delete_traces(self, indices)\n", " | Delete data traces from a graph.\n", " | \n", " | Args:\n", " | indices (list[int]): The indices of the traces to be removed\n", " | \n", " | Example - Delete the 2nd trace:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget('https://plotly.com/~chris/3979')\n", " | display(graph)\n", " | \n", " | \n", " | graph.delete_traces([1])\n", " | ```\n", " | \n", " | extend_traces(self, update, indices=(0,), max_points=None)\n", " | Append data points to existing traces in the Plotly graph.\n", " | \n", " | Args:\n", " | update (dict):\n", " | dict where keys are the graph attribute strings\n", " | and values are arrays of arrays with values to extend.\n", " | \n", " | Each array in the array will extend a trace.\n", " | \n", " | Valid keys include:\n", " | 'x', 'y', 'text,\n", " | 'marker.color', 'marker.size', 'marker.symbol',\n", " | 'marker.line.color', 'marker.line.width'\n", " | \n", " | indices (list, int):\n", " | Specify which traces to apply the `update` dict to.\n", " | If indices are not given, the update will apply to\n", " | the traces in order.\n", " | \n", " | max_points (int or dict, optional):\n", " | If specified, then only show the `max_points` most\n", " | recent points in the graph.\n", " | This is useful to prevent traces from becoming too\n", " | large (and slow) or for creating \"windowed\" graphs\n", " | in monitoring applications.\n", " | \n", " | To set max_points to different values for each trace\n", " | or attribute, set max_points to a dict mapping keys\n", " | to max_points values. See the examples below.\n", " | \n", " | Examples:\n", " | Initialization - Start each example below with this setup:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget()\n", " | graph.plot([\n", " | {'x': [], 'y': []},\n", " | {'x': [], 'y': []}\n", " | ])\n", " | \n", " | display(graph)\n", " | ```\n", " | \n", " | Example 1 - Extend the first trace with x and y data\n", " | ```\n", " | graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},\n", " | indices=[0])\n", " | ```\n", " | \n", " | Example 2 - Extend the second trace with x and y data\n", " | ```\n", " | graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},\n", " | indices=[1])\n", " | ```\n", " | \n", " | Example 3 - Extend the first two traces with x and y data\n", " | ```\n", " | graph.extend_traces({\n", " | 'x': [[1, 2, 3], [2, 3, 4]],\n", " | 'y': [[10, 20, 30], [3, 4, 3]]\n", " | }, indices=[0, 1])\n", " | ```\n", " | \n", " | Example 4 - Extend the first trace with x and y data and\n", " | limit the length of data in that trace to 50\n", " | points.\n", " | ```\n", " | \n", " | graph.extend_traces({\n", " | 'x': [range(100)],\n", " | 'y': [range(100)]\n", " | }, indices=[0, 1], max_points=50)\n", " | ```\n", " | \n", " | Example 5 - Extend the first and second trace with x and y data\n", " | and limit the length of data in the first trace to\n", " | 25 points and the second trace to 50 points.\n", " | ```\n", " | new_points = range(100)\n", " | graph.extend_traces({\n", " | 'x': [new_points, new_points],\n", " | 'y': [new_points, new_points]\n", " | },\n", " | indices=[0, 1],\n", " | max_points={\n", " | 'x': [25, 50],\n", " | 'y': [25, 50]\n", " | }\n", " | )\n", " | ```\n", " | \n", " | Example 6 - Update other attributes, like marker colors and\n", " | sizes and text\n", " | ```\n", " | # Initialize a plot with some empty attributes\n", " | graph.plot([{\n", " | 'x': [],\n", " | 'y': [],\n", " | 'text': [],\n", " | 'marker': {\n", " | 'size': [],\n", " | 'color': []\n", " | }\n", " | }])\n", " | # Append some data into those attributes\n", " | graph.extend_traces({\n", " | 'x': [[1, 2, 3]],\n", " | 'y': [[10, 20, 30]],\n", " | 'text': [['A', 'B', 'C']],\n", " | 'marker.size': [[10, 15, 20]],\n", " | 'marker.color': [['blue', 'red', 'orange']]\n", " | }, indices=[0])\n", " | ```\n", " | \n", " | Example 7 - Live-update a graph over a few seconds\n", " | ```\n", " | import time\n", " | \n", " | graph.plot([{'x': [], 'y': []}])\n", " | for i in range(10):\n", " | graph.extend_traces({\n", " | 'x': [[i]],\n", " | 'y': [[i]]\n", " | }, indices=[0])\n", " | \n", " | time.sleep(0.5)\n", " | ```\n", " | \n", " | hover(self, *hover_objs)\n", " | Show hover labels over the points specified in hover_obj.\n", " | \n", " | Hover labels are the labels that normally appear when the\n", " | mouse hovers over points in the plotly graph.\n", " | \n", " | Args:\n", " | hover_objs (tuple of dicts):\n", " | Specifies which points to place hover labels over.\n", " | \n", " | The location of the hover labels is described by a dict with\n", " | keys and'xval' and/or 'yval' or 'curveNumber' and 'pointNumber'\n", " | and optional keys 'hovermode' and 'subplot'\n", " | \n", " | 'xval' and 'yval' specify the (x, y) coordinates to\n", " | place the label.\n", " | 'xval' and 'yval need to be close to a point drawn in a graph.\n", " | \n", " | 'curveNumber' and 'pointNumber' specify the trace number and\n", " | the index theof the point in that trace respectively.\n", " | \n", " | 'subplot' describes which axes to the coordinates refer to.\n", " | By default, it is equal to 'xy'. For example, to specify the\n", " | second x-axis and the third y-axis, set 'subplot' to 'x2y3'\n", " | \n", " | 'hovermode' is either 'closest', 'x', or 'y'.\n", " | When set to 'x', all data sharing the same 'x' coordinate will\n", " | be shown on screen with corresponding trace labels.\n", " | When set to 'y' all data sharing the same 'y' coordinates will\n", " | be shown on the screen with corresponding trace labels.\n", " | When set to 'closest', information about the data point closest\n", " | to where the viewer is hovering will appear.\n", " | \n", " | Note: If 'hovermode' is 'x', only 'xval' needs to be set.\n", " | If 'hovermode' is 'y', only 'yval' needs to be set.\n", " | If 'hovermode' is 'closest', 'xval' and 'yval' both\n", " | need to be set.\n", " | \n", " | Note: 'hovermode' can be toggled by the user in the graph\n", " | toolbar.\n", " | \n", " | Note: It is not currently possible to apply multiple hover\n", " | labels to points on different axes.\n", " | \n", " | Note: `hover` can only be called with multiple dicts if\n", " | 'curveNumber' and 'pointNumber' are the keys of the dicts\n", " | \n", " | Examples:\n", " | Initialization - Start each example below with this setup:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget('https://plotly.com/~chris/3979')\n", " | display(graph)\n", " | ```\n", " | \n", " | Example 1 - Apply a label to the (x, y) point (3, 2)\n", " | ```\n", " | graph.hover({'xval': 3, 'yval': 2, 'hovermode': 'closest'})\n", " | ```\n", " | \n", " | Example 2 -Apply a labels to all the points with the x coordinate 3\n", " | ```\n", " | graph.hover({'xval': 3, 'hovermode': 'x'})\n", " | ```\n", " | \n", " | Example 3 - Apply a label to the first point of the first trace\n", " | and the second point of the second trace.\n", " | ```\n", " | graph.hover({'curveNumber': 0, 'pointNumber': 0},\n", " | {'curveNumber': 1, 'pointNumber': 1})\n", " | ```\n", " | \n", " | on_click(self, callback, remove=False)\n", " | Assign a callback to click events propagated\n", " | by clicking on point(s) in the Plotly graph.\n", " | \n", " | Args:\n", " | callback (function): Callback function this is called\n", " | on click events with the signature:\n", " | callback(widget, hover_obj) -> None\n", " | \n", " | Args:\n", " | widget (GraphWidget): The current instance\n", " | of the graph widget that this callback is assigned to.\n", " | \n", " | click_obj (dict): a nested dict that describes\n", " | which point(s) were clicked on.\n", " | \n", " | click_obj example:\n", " | [\n", " | {\n", " | 'curveNumber': 1,\n", " | 'pointNumber': 2,\n", " | 'x': 4,\n", " | 'y': 14\n", " | }\n", " | ]\n", " | \n", " | remove (bool, optional): If False, attach the callback.\n", " | If True, remove the callback. Defaults to False.\n", " | \n", " | \n", " | Returns:\n", " | None\n", " | \n", " | Example:\n", " | ```\n", " | from IPython.display import display\n", " | def message_handler(widget, msg):\n", " | display(widget._graph_url)\n", " | display(msg)\n", " | \n", " | g = GraphWidget('https://plotly.com/~chris/3375')\n", " | display(g)\n", " | \n", " | g.on_click(message_handler)\n", " | ```\n", " | \n", " | on_hover(self, callback, remove=False)\n", " | Assign a callback to hover events propagated\n", " | by hovering over points in the Plotly graph.\n", " | \n", " | Args:\n", " | callback (function): Callback function this is called\n", " | on hover events with the signature:\n", " | callback(widget, hover_obj) -> None\n", " | \n", " | Args:\n", " | widget (GraphWidget): The current instance\n", " | of the graph widget that this callback is assigned to.\n", " | \n", " | hover_obj (dict): a nested dict that describes\n", " | which point(s) was hovered over.\n", " | \n", " | hover_obj example:\n", " | [\n", " | {\n", " | 'curveNumber': 1,\n", " | 'pointNumber': 2,\n", " | 'x': 4,\n", " | 'y': 14\n", " | }\n", " | ]\n", " | \n", " | remove (bool, optional): If False, attach the callback.\n", " | If True, remove the callback. Defaults to False.\n", " | \n", " | \n", " | Returns:\n", " | None\n", " | \n", " | Example:\n", " | ```\n", " | from IPython.display import display\n", " | def message_handler(widget, hover_msg):\n", " | display(widget._graph_url)\n", " | display(hover_msg)\n", " | \n", " | g = GraphWidget('https://plotly.com/~chris/3375')\n", " | display(g)\n", " | \n", " | g.on_hover(message_handler)\n", " | ```\n", " | \n", " | on_zoom(self, callback, remove=False)\n", " | Assign a callback to zoom events propagated\n", " | by zooming in regions in the Plotly graph.\n", " | \n", " | Args:\n", " | callback (function): Callback function this is called\n", " | on zoom events with the signature:\n", " | callback(widget, ranges) -> None\n", " | \n", " | Args:\n", " | widget (GraphWidget): The current instance\n", " | of the graph widget that this callback is assigned to.\n", " | \n", " | ranges (dict): A description of the\n", " | region that was zoomed into.\n", " | \n", " | ranges example:\n", " | {\n", " | 'x': [1.8399058038561549, 2.16443359662],\n", " | 'y': [4.640902872777017, 7.855677154582]\n", " | }\n", " | \n", " | remove (bool, optional): If False, attach the callback.\n", " | If True, remove the callback. Defaults to False.\n", " | \n", " | Returns:\n", " | None\n", " | \n", " | Example:\n", " | ```\n", " | from IPython.display import display\n", " | def message_handler(widget, ranges):\n", " | display(widget._graph_url)\n", " | display(ranges)\n", " | \n", " | g = GraphWidget('https://plotly.com/~chris/3375')\n", " | display(g)\n", " | \n", " | g.on_zoom(message_handler)\n", " | ```\n", " | \n", " | plot(self, figure_or_data, validate=True)\n", " | Plot figure_or_data in the Plotly graph widget.\n", " | \n", " | Args:\n", " | figure_or_data (dict, list, or plotly.graph_obj object):\n", " | The standard Plotly graph object that describes Plotly\n", " | graphs as used in `plotly.plotly.plot`. See examples\n", " | of the figure_or_data in https://plotly.com/python/\n", " | \n", " | Returns: None\n", " | \n", " | Example 1 - Graph a scatter plot:\n", " | ```\n", " | from plotly.graph_objs import Scatter\n", " | g = GraphWidget()\n", " | g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])\n", " | ```\n", " | \n", " | Example 2 - Graph a scatter plot with a title:\n", " | ```\n", " | from plotly.graph_objs import Scatter, Figure, Data\n", " | fig = Figure(\n", " | data = Data([\n", " | Scatter(x=[1, 2, 3], y=[20, 15, 13])\n", " | ]),\n", " | layout = Layout(title='Experimental Data')\n", " | )\n", " | \n", " | g = GraphWidget()\n", " | g.plot(fig)\n", " | ```\n", " | \n", " | Example 3 - Clear a graph widget\n", " | ```\n", " | from plotly.graph_objs import Scatter, Figure\n", " | g = GraphWidget()\n", " | g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])\n", " | \n", " | # Now clear it\n", " | g.plot({}) # alternatively, g.plot(Figure())\n", " | ```\n", " | \n", " | relayout(self, layout)\n", " | Update the layout of the Plotly graph.\n", " | \n", " | Args:\n", " | layout (dict):\n", " | dict where keys are the graph attribute strings\n", " | and values are the value of the graph attribute.\n", " | \n", " | To update graph objects that are nested, like\n", " | the title of an axis, combine the keys with a period\n", " | e.g. `xaxis.title`. To set a value of an element in an array,\n", " | like an axis's range, use brackets, e.g. 'xaxis.range[0]'.\n", " | To replace an entire nested object, just specify the value to\n", " | the sub-object. See example 4 below.\n", " | \n", " | See all of the layout attributes in our reference documentation\n", " | https://plotly.com/python/reference/#Layout\n", " | Or by calling `help` on `plotly.graph_objs.Layout`\n", " | \n", " | Examples - Start each example below with this setup:\n", " | Initialization:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget('https://plotly.com/~chris/3979')\n", " | display(graph)\n", " | ```\n", " | \n", " | Example 1 - Update the title\n", " | ```\n", " | graph.relayout({'title': 'Experimental results'})\n", " | ```\n", " | \n", " | Example 2 - Update the xaxis range\n", " | ```\n", " | graph.relayout({'xaxis.range': [-1, 6]})\n", " | ```\n", " | \n", " | Example 3 - Update the first element of the xaxis range\n", " | ```\n", " | graph.relayout({'xaxis.range[0]': -3})\n", " | ```\n", " | \n", " | Example 4 - Replace the entire xaxis object\n", " | ```\n", " | graph.relayout({'xaxis': {'title': 'Experimental results'}})\n", " | ```\n", " | \n", " | reorder_traces(self, current_indices, new_indices=None)\n", " | Reorder the traces in a graph.\n", " | \n", " | The order of the traces determines the order of the legend entries\n", " | and the layering of the objects drawn in the graph, i.e. the first\n", " | trace is drawn first and the second trace is drawn on top of the\n", " | first trace.\n", " | \n", " | Args:\n", " | current_indices (list[int]): The index of the traces to reorder.\n", " | \n", " | new_indices (list[int], optional): The index of the traces\n", " | specified by `current_indices` after ordering.\n", " | If None, then move the traces to the end.\n", " | \n", " | Examples:\n", " | Example 1 - Move the first trace to the second to last\n", " | position, the second trace to the last position\n", " | ```\n", " | graph.move_traces([0, 1])\n", " | ```\n", " | \n", " | Example 2 - Move the first trace to the second position,\n", " | the second trace to the first position.\n", " | ```\n", " | graph.move_traces([0], [1])\n", " | ```\n", " | \n", " | restyle(self, update, indices=None)\n", " | Update the style of existing traces in the Plotly graph.\n", " | \n", " | Args:\n", " | update (dict):\n", " | dict where keys are the graph attribute strings\n", " | and values are the value of the graph attribute.\n", " | \n", " | To update graph objects that are nested, like\n", " | a marker's color, combine the keys with a period,\n", " | e.g. `marker.color`. To replace an entire nested object,\n", " | like `marker`, set the value to the object.\n", " | See Example 2 below.\n", " | \n", " | To update an attribute of multiple traces, set the\n", " | value to an list of values. If the list is shorter\n", " | than the number of traces, the values will wrap around.\n", " | Note: this means that for values that are naturally an array,\n", " | like `x` or `colorscale`, you need to wrap the value\n", " | in an extra array,\n", " | i.e. {'colorscale': [[[0, 'red'], [1, 'green']]]}\n", " | \n", " | You can also supply values to different traces with the\n", " | indices argument.\n", " | \n", " | See all of the graph attributes in our reference documentation\n", " | here: https://plotly.com/python/reference or by calling `help` on\n", " | graph objects in `plotly.graph_objs`.\n", " | \n", " | indices (list, optional):\n", " | Specify which traces to apply the update dict to.\n", " | Negative indices are supported.\n", " | If indices are not given, the update will apply to\n", " | *all* traces.\n", " | \n", " | Examples:\n", " | Initialization - Start each example below with this setup:\n", " | ```\n", " | from plotly.widgets import GraphWidget\n", " | from IPython.display import display\n", " | \n", " | graph = GraphWidget()\n", " | display(graph)\n", " | ```\n", " | \n", " | Example 1 - Set `marker.color` to red in every trace in the graph\n", " | ```\n", " | graph.restyle({'marker.color': 'red'})\n", " | ```\n", " | \n", " | Example 2 - Replace `marker` with {'color': 'red'}\n", " | ```\n", " | graph.restyle({'marker': {'color': red'}})\n", " | ```\n", " | \n", " | Example 3 - Set `marker.color` to red\n", " | in the first trace of the graph\n", " | ```\n", " | graph.restyle({'marker.color': 'red'}, indices=[0])\n", " | ```\n", " | \n", " | Example 4 - Set `marker.color` of all of the traces to\n", " | alternating sequences of red and green\n", " | ```\n", " | graph.restyle({'marker.color': ['red', 'green']})\n", " | ```\n", " | \n", " | Example 5 - Set just `marker.color` of the first two traces\n", " | to red and green\n", " | ```\n", " | graph.restyle({'marker.color': ['red', 'green']}, indices=[0, 1])\n", " | ```\n", " | \n", " | Example 6 - Set multiple attributes of all of the traces\n", " | ```\n", " | graph.restyle({\n", " | 'marker.color': 'red',\n", " | 'line.color': 'green'\n", " | })\n", " | ```\n", " | \n", " | Example 7 - Update the data of the first trace\n", " | ```\n", " | graph.restyle({\n", " | 'x': [[1, 2, 3]],\n", " | 'y': [[10, 20, 30]],\n", " | }, indices=[0])\n", " | ```\n", " | \n", " | Example 8 - Update the data of the first two traces\n", " | ```\n", " | graph.restyle({\n", " | 'x': [[1, 2, 3],\n", " | [1, 2, 4]],\n", " | 'y': [[10, 20, 30],\n", " | [5, 8, 14]],\n", " | }, indices=[0, 1])\n", " | ```\n", " | \n", " | save(self, ignore_defaults=False, filename='')\n", " | Save a copy of the current state of the widget in plotly.\n", " | \n", " | :param (bool) ignore_defaults: Auto-fill in unspecified figure keys?\n", " | :param (str) filename: Name of the file on plotly.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | url\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from ipywidgets.widgets.domwidget.DOMWidget:\n", " | \n", " | add_class(self, className)\n", " | Adds a class to the top level element of the widget.\n", " | \n", " | Doesn't add the class if it already exists.\n", " | \n", " | remove_class(self, className)\n", " | Removes a class from the top level element of the widget.\n", " | \n", " | Doesn't remove the class if it doesn't exist.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from ipywidgets.widgets.domwidget.DOMWidget:\n", " | \n", " | layout\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from ipywidgets.widgets.widget.Widget:\n", " | \n", " | __del__(self)\n", " | Object disposal\n", " | \n", " | add_traits(self, **traits)\n", " | Dynamically add trait attributes to the Widget.\n", " | \n", " | close(self)\n", " | Close method.\n", " | \n", " | Closes the underlying comm.\n", " | When the comm is closed, all of the widget views are automatically\n", " | removed from the front-end.\n", " | \n", " | get_state(self, key=None, drop_defaults=False)\n", " | Gets the widget state, or a piece of it.\n", " | \n", " | Parameters\n", " | ----------\n", " | key : unicode or iterable (optional)\n", " | A single property's name or iterable of property names to get.\n", " | \n", " | Returns\n", " | -------\n", " | state : dict of states\n", " | metadata : dict\n", " | metadata for each field: {key: metadata}\n", " | \n", " | get_view_spec(self)\n", " | \n", " | hold_sync(*args, **kwds)\n", " | Hold syncing any state until the outermost context manager exits\n", " | \n", " | notify_change(self, change)\n", " | Called when a property has changed.\n", " | \n", " | on_displayed(self, callback, remove=False)\n", " | (Un)Register a widget displayed callback.\n", " | \n", " | Parameters\n", " | ----------\n", " | callback: method handler\n", " | Must have a signature of::\n", " | \n", " | callback(widget, **kwargs)\n", " | \n", " | kwargs from display are passed through without modification.\n", " | remove: bool\n", " | True if the callback should be unregistered.\n", " | \n", " | on_msg(self, callback, remove=False)\n", " | (Un)Register a custom msg receive callback.\n", " | \n", " | Parameters\n", " | ----------\n", " | callback: callable\n", " | callback will be passed three arguments when a message arrives::\n", " | \n", " | callback(widget, content, buffers)\n", " | \n", " | remove: bool\n", " | True if the callback should be unregistered.\n", " | \n", " | open(self)\n", " | Open a comm to the frontend if one isn't already open.\n", " | \n", " | send(self, content, buffers=None)\n", " | Sends a custom msg to the widget model in the front-end.\n", " | \n", " | Parameters\n", " | ----------\n", " | content : dict\n", " | Content of the message to send.\n", " | buffers : list of binary buffers\n", " | Binary buffers to send with message\n", " | \n", " | send_state(self, key=None)\n", " | Sends the widget state, or a piece of it, to the front-end.\n", " | \n", " | Parameters\n", " | ----------\n", " | key : unicode, or iterable (optional)\n", " | A single property's name or iterable of property names to sync with the front-end.\n", " | \n", " | set_state(self, sync_data)\n", " | Called when a state is received from the front-end.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods inherited from ipywidgets.widgets.widget.Widget:\n", " | \n", " | get_manager_state(drop_defaults=False)\n", " | \n", " | handle_comm_opened(comm, msg)\n", " | Static method, called when a widget is constructed.\n", " | \n", " | on_widget_constructed(callback)\n", " | Registers a callback to be called when a widget is constructed.\n", " | \n", " | The callback must have the following signature:\n", " | callback(widget)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from ipywidgets.widgets.widget.Widget:\n", " | \n", " | comm\n", " | A trait whose value must be an instance of a specified class.\n", " | \n", " | The value can also be an instance of a subclass of the specified class.\n", " | \n", " | Subclasses can declare default classes by overriding the klass attribute\n", " | \n", " | keys\n", " | An instance of a Python list.\n", " | \n", " | model_id\n", " | Gets the model id of this widget.\n", " | \n", " | If a Comm doesn't exist yet, a Comm will be created automagically.\n", " | \n", " | msg_throttle\n", " | An int trait.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from ipywidgets.widgets.widget.Widget:\n", " | \n", " | widget_types = {'Jupyter.Accordion': " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Collecting git+https://github.com/plotly/publisher.git\n", " Cloning https://github.com/plotly/publisher.git to /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-req-build-Iawk2h\n", "Building wheels for collected packages: publisher\n", " Running setup.py bdist_wheel for publisher ... \u001b[?25ldone\n", "\u001b[?25h Stored in directory: /private/var/folders/tc/bs9g6vrd36q74m5t8h9cgphh0000gn/T/pip-ephem-wheel-cache-kkF5o1/wheels/99/3e/a0/fbd22ba24cca72bdbaba53dbc23c1768755fb17b3af0f33966\n", "Successfully built publisher\n", "Installing collected packages: publisher\n", " Found existing installation: publisher 0.11\n", " Uninstalling publisher-0.11:\n", " Successfully uninstalled publisher-0.11\n", "Successfully installed publisher-0.11\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/nbconvert.py:13: ShimWarning:\n", "\n", "The `IPython.nbconvert` package has been deprecated since IPython 4.0. You should import from nbconvert instead.\n", "\n", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/publisher/publisher.py:53: UserWarning:\n", "\n", "Did you \"Save\" this notebook before running this command? Remember to save, always save.\n", "\n" ] } ], "source": [ "from IPython.display import display, HTML\n", "\n", "display(HTML(''))\n", "display(HTML(''))\n", "\n", "! pip install git+https://github.com/plotly/publisher.git --upgrade\n", " \n", "import publisher\n", "publisher.publish(\n", " 'slider_example.ipynb', 'python/slider-widget/', 'IPython Widgets | plotly',\n", " 'Interacting with Plotly charts using Sliders',\n", " title = 'Slider Widget with Plotly',\n", " name = 'Slider Widget with Plotly',\n", " has_thumbnail='true', thumbnail='thumbnail/ipython_widgets.jpg', \n", " language='python', page_type='example_index', \n", " display_as='chart_events', order=20,\n", " ipynb= '~notebook_demo/91')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 1 }