#!/usr/bin/env python # coding: utf-8 # # Live-updating plots with zmq, bqplot, and widgets # Start a simple zmq data publishing service, as a demo: # In[1]: get_ipython().run_cell_magic('writefile', 'publisher.py', "\nimport time\nimport pickle\n\nimport numpy as np\nimport zmq\n\nsize = 100\nscale = 100\nurl = 'tcp://127.0.0.1:5555'\n\ndef main():\n ctx = zmq.Context.instance()\n pub = ctx.socket(zmq.PUB)\n pub.bind(url)\n while True:\n data = np.cumsum(np.random.randn(size) * scale)\n md = {\n 'shape': data.shape,\n 'dtype': data.dtype,\n }\n pub.send_multipart([\n pickle.dumps(md, pickle.HIGHEST_PROTOCOL),\n data,\n ])\n time.sleep(1)\n\nif __name__ == '__main__':\n main()\n") # In[2]: from subprocess import Popen publisher = Popen([sys.executable, 'publisher.py']) # Make an ipywidgets-based plot with bqplot: # In[5]: import numpy as np import bqplot as bq size = 100 scale = 100. np.random.seed(0) x_data = np.arange(size) y_data = np.cumsum(np.random.randn(size) * scale) x_sc = bq.LinearScale() y_sc = bq.LinearScale() ax_x = bq.Axis(label='X', scale=x_sc, grid_lines='solid') ax_y = bq.Axis(label='Y', scale=y_sc, orientation='vertical', grid_lines='solid') line = bq.Lines(x=x_data, y=y_data, scales={'x': x_sc, 'y': y_sc}) fig = bq.Figure(axes=[ax_x, ax_y], marks=[line], title='Live Updates!') fig # Subscribe to our data-publisher, updating # In[4]: import pickle def subscribe(url): ctx = zmq.Context.instance() s = ctx.socket(zmq.SUB) s.connect('tcp://127.0.0.1:5555') s.subscribe = b'' while True: pmd, buf = s.recv_multipart() md = pickle.loads(pmd) a = np.frombuffer(buf, dtype=md['dtype']).reshape(md['shape']) # setting line.y updates the plot above line.y = a from threading import Thread subscriber = Thread(target=subscribe, args=('tcp://127.0.0.1:5555',)) subscriber.start()