[Python] Changing point color depending on value in real-time plotting with Bokeh

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Bokeh in an experiment to plot data in realtime and the library provides a convenient way to do that.

    Here a snippet of my code to accomplish this tasks:

    # do the imports
    import pandas as pd
    import numpy as np
    import time
    from bokeh.plotting import *
    from bokeh.models import ColumnDataSource

    # here is simulated fake time series data
    ts = pd.date_range("8:00", "10:00", freq="5S")
    ts.name = 'timestamp'
    ms = pd.Series(np.arange(0, len(ts)), index=ts)
    ms.name = 'measurement'
    data = pd.DataFrame(ms)
    data['state'] = np.random.choice(3, len(ts))
    data['observation'] = np.random.choice(2, len(ts))
    data.reset_index(inplace=True)
    data.head()


    This is how the data looks like. [​IMG]

    Next I have used the following snipped to push the data to the server in real time

    output_server("observation")

    p = figure(plot_width=800, plot_height=400, x_axis_type="datetime")
    x = np.array(data.head(2).timestamp, dtype=np.datetime64)
    y = np.array(data.head(2).observation)
    p.diamond_cross(x,y, size=30, fill_color=None, line_width=2, name='observation')
    show(p)

    renderer = p.select(dict(name="observation"))[0]
    ds = renderer.data_source

    for mes in range(len(data)):

    x = np.append(x, np.datetime64(data.loc[mes].timestamp))
    y = np.append(y, np.int64(data.loc[mes].observation))
    ds.data["x"] = x
    ds.data["y"] = y

    ds._dirty = True
    cursession().store_objects(ds)
    time.sleep(.1)


    This produces a very nice result, however I need to change the color of each data point conditioned on a value.

    In this case, the condition is the state variable which takes three values -- 0, 1, and 2. So my data should be able to reflect that.

    [​IMG]

    Continue reading...

Compartilhe esta Página