Realtime bokeh plotting with asyncio

Now and then the need arises to plot data in realtime. I know how simple this is using LabView but I always pefer Python for its versatility in data analysis.
However when it comes to plotting data in realtime I have never seen any easy solution for Python.

For my daily plotting needs I mostly use matplotlib but the Bokeh project is currently ahead when it comes to interactive plotting for the web.

Another exciting development has been Python3's asyncio which is python's native approach to an event driven framework. This puts python in the spotlight for io-bound applications for which people would use node.js.

Combing the Bokeh and asyncio allows building an interactive, realtime plotting application in less then 30 lines of code. I did not find any official documentation on how to do this so I decided to provide my own adapted from the official example here. I suggest to have a look at the official example to get a better understanding how the asyncio version works. In essence we replace the curdoc().add_periodic_callback(update, 50) and the session.loop_until_closed() functions by the asyncio equivalent of loop.run_until_complete(update()). For this to work the update function then has to be a coroutine, which is one of the concepts asyncio brings to the table. An introduction to this can be found here. Then asyncio is also used to spawn a background process of 'tail -f +n 1' which first outputs the content of a file to stdout and then keeps following the end of the file as new lines are added. This is where the asynchronous part comes in: in a naive implementation waiting for a new line to appear blocks the execution. But now we can give python time to do something else in the meantime and the application remains responsive.

Comments

Popular posts from this blog

Setting up a Raspberry Pi for OSX using a direct ethernet connection

cacti and friends

OpenDNS Fritzbox Howto