Line glyph of a data-set drawn with alternating colors

Hello,
I have a data series that is analysed in chunks/slices. In order to visualize the border of on chunc to the next I would like to use two colors that alternate from one chunc to the next (green, red, green, red, … ) I tried to realize that that with a single CDS and two CDSViews. Unfortunately CDSViews seem not to work “with glyphs with connected topology such as Line or Patch” at least that’s what the error message says.
However, i need to have the chart as line and not as points!
Is there a simple alternative to the not working “but elegant” CDSView method?

If this text description is unclear the following code may be better to understand the challenge:

from bokeh.models import BooleanFilter, CDSView, ColumnDataSource
from bokeh.plotting import figure, show
import numpy as np

x=4*np.pi*np.arange(100)/100.0
source = ColumnDataSource(data=dict(x=x, 
                                    y=np.sin(x)))

bools = [True if y >= 0 else False for y in source.data['y']]
view1 = CDSView(filter=BooleanFilter(bools))       
view2 = CDSView(filter=BooleanFilter([not(t) for t in bools])) # inverted Filter

p2 = figure(height=300, width=600)

# this works, but doesn't help
p2.circle(x="x", y="y", color="green", size=3, source=source, view=view1)
p2.circle(x="x", y="y", color="red",  size=3, source=source, view=view2)

# this would help, but doesn't work
# p2.line(x="x", y="y", color="green", source=source, view=view1)
# p2.line(x="x", y="y", color="red",  source=source, view=view2)

show(p2)

Any suggestion welcome.

A line is a single entity with a single color. The equivalent glyph that renders multiple lines with potentially different colors each is a multi_line glyph. You’ll have to rearrange your x and y values to be lists of coordinates, one per line.

See <no title> — Bokeh 3.0.3 Documentation for information on multi_line glyph.

1 Like

Thanks for the quick response.
In fact I had a prior look at multi_line, but missed the information on how to provide multiple colors.
Encouraged by your response, I finally found a solution:

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
import numpy as np

xs=[(i*np.pi + np.pi*np.arange(25)/25) for i in range(4)]
source = ColumnDataSource(data=dict(xs=xs, 
                                    ys=[np.sin(x) for x in xs],
                                    color=["green","red","green","red"]))

p2 = figure(height=300, width=600)
p2.multi_line(xs="xs", ys="ys", line_color="color", 
              source=source, line_width = 2
              )
show(p2)

An important step was to provide the color(s) as a list within the CDS.
(I think this is not at all clear from the docs.)

Thanks again, this helped a lot!
I hope my sample code will help others, too.

Thomas

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.