This example notebook is not up-to-date with the latest version of Plotly's Python API (version 1.0.*).
Refer to Plotly's Python User Guide and more specifically section 7 for an updated version of this notebook.
Readers looking for info about the nuts and bolts of Plotly's streaming API should refer to this link.
import plotly
import socket
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'][4]
stream_server = 'http://stream.plot.ly'
# Initialize your plotly object
p = plotly.plotly(username, api_key)
p.iplot([{'x': [], 'y': [], 'type': 'scatter',
'stream': {'token': stream_token, 'maxpoints': 100}
}], layout={},
filename='Sockets Example', fileopt='overwrite')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stream.plot.ly', 80))
# "Streaming" is really just a HTTP chunked request
# As per HTTP 1.1, each line must be broken with \r\n
# The headers and the body are broken with \r\n\r\n
# See here for reference: http://en.wikipedia.org/wiki/Chunked_transfer_encoding#Encoded_data
# Plotly requires an additional header: plotly-streamtoken
# Send the headers
sock.send("POST / HTTP/1.1\r\n")
sock.send("Host: 127.0.0.1\r\n")
sock.send("User-Agent: Python\r\n")
sock.send("Transfer-Encoding: chunked\r\n")
sock.send("Connection: close\r\n")
sock.send("plotly-streamtoken: "+stream_token)
sock.send("\r\n\r\n")
# Now send the body of the message
# Each "chunk" of data must be preceded with the length of the chunk, in hex
s = json.dumps({'x': 1, 'y': 1})+'\n' # Plotly formatted JSON data
sock.send(format(len(s), 'x')+'\r\n') # Sending the length of the data in hex
sock.send(s+'\r\n') # Sending the data
# Now send the next chunk, with new data ...
s = json.dumps({'x': 2, 'y': 2})+'\n'
sock.send(format(len(s), 'x')+'\r\n')
sock.send(s+'\r\n')
# And another ...
s = json.dumps({'x': 3, 'y': 3})+'\n'
sock.send(format(len(s), 'x')+'\r\n')
sock.send(s+'\r\n')
# Chunked requests end with these lines
sock.send("0\r\n")
sock.send("\r\n")
sock.close()
http://nbviewer.ipython.org/github/plotly/Streaming-Demos/tree/master/IPython%20examples/
https://github.com/plotly/Streaming-Demos
# 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()