Search code examples
python-3.xplotwindows-10bokeh

Bokeh line plot connects every points to the first point, what is wrong?


I'm trying to feed live data and plot it against datetime. However every point is connected to the first point by a line. What is wrong here? Thank you for any help. (I saved this as test.py and ran bokeh serve --show test.py in the command prompt.)

from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, DatetimeTickFormatter
from bokeh.plotting import figure
import numpy as np

x, y = [], []
source = ColumnDataSource(dict(time=x, data=y))

p = figure(x_axis_type='datetime')
p.line(x='time', y='data', source=source)
p.xaxis.formatter = DatetimeTickFormatter(days="%m/%d %H:%M", months="%m/%d %H:%M",
                                          hours="%m/%d %H:%M", minutes="%m/%d %H:%M")


def update():
    x.append(np.datetime64('now'))
    y.append(np.random.rand())
    source.stream(dict(time=x, data=y), 100)


curdoc().add_root(p)
curdoc().add_periodic_callback(update, 1000)
curdoc().title = "random"

It looks like something shown below: enter image description here


Solution

  • stream is for adding new points to a data source. You are continually accumulating all points from every update, and thus re-streaming old points you have already been sent. There is no need to append anything, send only the actual new points, and nothing else:

    def update():
        x = [np.datetime64('now')]
        y = [np.random.rand()]
        source.stream(dict(time=x, data=y), 100)