{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Warning!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example notebook is not up-to-date with the latest version of Plotly's Python API (version 1.0.\\*). \n", "\n", "Refer to Plotly's Python [User Guide](http://nbviewer.ipython.org/github/plotly/python-user-guide/blob/master/s00_homepage/s00_homepage.ipynb) \n", "and more specifically [section 7](http://nbviewer.ipython.org/github/plotly/python-user-guide/blob/master/s7_streaming/s7_streaming.ipynb) for an updated version of this notebook.\n", "\n", "Readers looking for info about the nuts and bolts of Plotly's streaming API should refer to [this link](https://plot.ly/streaming/).\n", "\n", "
" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Streaming to plotly with Python's httplib library" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plotly Streaming enables your plotly graphs to update in real-time, without refereshing your browser.\n", "\n", "Learn more about real-time streaming graphs with plotly here:\n", "\n", "[https://github.com/plotly/streaming-demos](https://github.com/plotly/streaming-demos)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import plotly" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "# Fill in the config.json file in this directory with your plotly username, \n", "# plotly API key, and your generated plotly streaming tokens\n", "# Sign up to plotly here: https://plot.ly/ssu\n", "# View your API key and streaming tokens here: https://plot.ly/settings\n", "\n", "import json\n", "with open('./config_chris.json') as config_file:\n", " plotly_user_config = json.load(config_file)\n", "\n", "username = plotly_user_config['plotly_username'] \n", "api_key = plotly_user_config['plotly_api_key']\n", "stream_token = plotly_user_config['plotly_streaming_tokens'][5]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This class is embedded in the plotly module: `plotly.stream`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import httplib\n", "import json\n", "\n", "class stream:\n", " def __init__(self, token):\n", " ''' plotly stream constructor\n", " token found at https://plot.ly/settings\n", " '''\n", " self.token = token\n", "\n", " def init(self):\n", " ''' Initialize a streaming connection to plotly \n", " '''\n", " self.conn = httplib.HTTPConnection('stream.plot.ly', 80)\n", " self.conn.putrequest('POST', '/')\n", " self.conn.putheader('Host', 'stream.plot.ly')\n", " self.conn.putheader('User-Agent', 'Python-Plotly')\n", " self.conn.putheader('Transfer-Encoding', 'chunked')\n", " self.conn.putheader('Connection', 'close')\n", " self.conn.putheader('plotly-streamtoken', self.token)\n", " self.conn.endheaders()\n", " \n", " def write(self, data):\n", " ''' Write data to plotly's streaming servers\n", "\n", " data is a plotly formatted data dict\n", " with data keys 'x', 'y', 'text', 'z', 'marker', 'line'\n", " 'x', 'y', 'text', and 'z' can have values of strings, numbers, or lists\n", " 'marker', and 'line' have dicts as values with keys 'size', 'color', 'symbol'\n", "\n", " Examples:\n", " {'x': 1, 'y': 2}\n", " {'x': [1, 2, 3], 'y': [10, 20, 30]}\n", " {'x': 1, 'y': 3, 'text': 'hover text'}\n", " {'x': 1, 'y': 3, 'marker': {'color': 'blue'}}\n", " {'z': [[1,2,3], [4,5,6]]}\n", " '''\n", " # plotly's streaming API takes new-line separated json objects\n", " msg = json.dumps(data)+'\\n'\n", " msglen = format(len(msg), 'x')\n", " # chunked encoding requests contain the messege length in hex, \\r\\n, and then the message\n", " self.conn.send('{msglen}\\r\\n{msg}\\r\\n'.format(msglen=msglen, msg=msg))\n", " \n", " def close(self):\n", " ''' Close connection to plotly's streaming servers\n", " '''\n", " self.conn.send('0\\r\\n\\r\\n')\n", " self.conn.close()\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "p = plotly.plotly(username, api_key)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "# Embed your plotly stream token inside the plot traces that you want to stream to\n", "# and initialize your stream with a REST call to plotly\n", "# Optionally specify the number of points that you would like to be plotted in your graph\n", "\n", "trace0 = {'x': [], 'y': [], 'stream': {'token': stream_token, 'maxpoints': 10}}\n", "\n", "p.iplot([trace0], filename='httplib example', fileopt='overwrite')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The graph is embedded in this notebook, but it can also be viewed at a unique url\n", "\n", "Click the `plotly - data and graph` link, here [https://plot.ly/~streaming-demos/23](https://plot.ly/~streaming-demos/23), to view the graph in its own window" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we'll initialize our stream, and send data to the graph, 1 point at a time" ] }, { "cell_type": "code", "collapsed": false, "input": [ "c = stream('7jig6zwb34')\n", "c.init()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "c.write({'x': 1, 'y': 1})" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Did you see that? A point was just drawn on the graph above. What's cool is that anyone who you have shared this graph with would've seen the graph update, in real-time. \n", "\n", "Let's fire another point" ] }, { "cell_type": "code", "collapsed": false, "input": [ "c.write({'x': 2, 'y': 2})" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "How fun! Let's loop" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import time\n", "from math import cos, sin\n", "for i in range(200):\n", " c.write({'x': cos(5*i/50.)*sin(i/50.), 'y': cos(5*i/50.)*cos(i/50.)})\n", " time.sleep(0.05)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember to close your stream!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "c.close()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Give it a try yourself!\n", "\n", "##### More Streaming IPython Notebooks:\n", "\n", "[http://nbviewer.ipython.org/github/plotly/Streaming-Demos/tree/master/IPython%20examples/](http://nbviewer.ipython.org/github/plotly/Streaming-Demos/tree/master/IPython%20examples/)\n", "\n", "##### More about Plotly Streaming \n", "\n", "[https://github.com/plotly/Streaming-Demos](https://github.com/plotly/Streaming-Demos)\n", "\n", "##### Get in touch!\n", "\n", "[http://twitter.com/plotlygraphs](@plotlygraphs)\n", "\n", "[https://facebook.com/plotly](https://facebook.com/plotly)\n", "\n", "" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# CSS styling within IPython notebook\n", "from IPython.core.display import HTML\n", "import urllib2\n", "def css_styling():\n", " url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css'\n", " styles = urllib2.urlopen(url).read()\n", " return HTML(styles)\n", "\n", "css_styling()" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }