import plotly # Fill in the config.json file in this directory with your plotly username, # plotly API key, and your generated plotly streaming tokens # Sign up to plotly here: https://plot.ly/ssu # View your API key and streaming tokens here: https://plot.ly/settings import json with open('./config_chris.json') as config_file: plotly_user_config = json.load(config_file) username = plotly_user_config['plotly_username'] api_key = plotly_user_config['plotly_api_key'] stream_token = plotly_user_config['plotly_streaming_tokens'][5] import httplib import json class stream: def __init__(self, token): ''' plotly stream constructor token found at https://plot.ly/settings ''' self.token = token def init(self): ''' Initialize a streaming connection to plotly ''' self.conn = httplib.HTTPConnection('stream.plot.ly', 80) self.conn.putrequest('POST', '/') self.conn.putheader('Host', 'stream.plot.ly') self.conn.putheader('User-Agent', 'Python-Plotly') self.conn.putheader('Transfer-Encoding', 'chunked') self.conn.putheader('Connection', 'close') self.conn.putheader('plotly-streamtoken', self.token) self.conn.endheaders() def write(self, data): ''' Write data to plotly's streaming servers data is a plotly formatted data dict with data keys 'x', 'y', 'text', 'z', 'marker', 'line' 'x', 'y', 'text', and 'z' can have values of strings, numbers, or lists 'marker', and 'line' have dicts as values with keys 'size', 'color', 'symbol' Examples: {'x': 1, 'y': 2} {'x': [1, 2, 3], 'y': [10, 20, 30]} {'x': 1, 'y': 3, 'text': 'hover text'} {'x': 1, 'y': 3, 'marker': {'color': 'blue'}} {'z': [[1,2,3], [4,5,6]]} ''' # plotly's streaming API takes new-line separated json objects msg = json.dumps(data)+'\n' msglen = format(len(msg), 'x') # chunked encoding requests contain the messege length in hex, \r\n, and then the message self.conn.send('{msglen}\r\n{msg}\r\n'.format(msglen=msglen, msg=msg)) def close(self): ''' Close connection to plotly's streaming servers ''' self.conn.send('0\r\n\r\n') self.conn.close() p = plotly.plotly(username, api_key) # Embed your plotly stream token inside the plot traces that you want to stream to # and initialize your stream with a REST call to plotly # Optionally specify the number of points that you would like to be plotted in your graph trace0 = {'x': [], 'y': [], 'stream': {'token': stream_token, 'maxpoints': 10}} p.iplot([trace0], filename='httplib example', fileopt='overwrite') c = stream('7jig6zwb34') c.init() c.write({'x': 1, 'y': 1}) c.write({'x': 2, 'y': 2}) import time from math import cos, sin for i in range(200): c.write({'x': cos(5*i/50.)*sin(i/50.), 'y': cos(5*i/50.)*cos(i/50.)}) time.sleep(0.05) c.close() # CSS styling within IPython notebook from IPython.core.display import HTML import urllib2 def css_styling(): url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css' styles = urllib2.urlopen(url).read() return HTML(styles) css_styling()