Search code examples
pythonbokehpaletteline-plot

Bokeh Line Plot: How to assign colors when plotting a large number of lines


I created a multiple line plot in Bokeh using a for loop (code below).

In the ouput example there are only two curves. In this case I can set a list of colors for each curve. But, How can I use one of the Bokeh palettes (e.g. Paired) if I need to plot a large number of curves? I'd like to automate this in order to avoid having to make color lists every time I increase the number of lines to be plotted.

import pandas as pd
import numpy as np
from bokeh.core.properties import value
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import ColumnDataSource, CDSView, GroupFilter, HoverTool

from bokeh.palettes import Paired

bokeh_test=pd.read_excel(data, 'bokeh line plot')
display(bokeh_test)


x   y
item        
A   4   0.0000
A   5   0.0000
A   36  39.8879
A   66  46.2022
A   97  32.9306
A   127 25.7896
A   158 21.9209
A   189 18.6405
B   6   4.4775
B   7   1.1710
B   8   0.0000
B   38  45.7007
B   68  61.6806
B   98  43.1121
B   129 25.0558
B   160 33.9727
B   190 32.0657
B   221 29.2204
B   251 24.9480

output_notebook()

source=ColumnDataSource(data=bokeh_test)

list1=np.unique(source.data['item']).tolist() # Getting a list for using with CDSView filters
# result = ['A', 'B']

tools = 'save, pan, box_zoom, reset, wheel_zoom,tap'
    
           
p = figure(plot_height=400, 
           plot_width=400,
           x_axis_label='x', 
           y_axis_label='y',
           toolbar_location='above',
           tools=tools
           )

color=['red', 'blue', 'green']

for i in range(len(list1)):
    view=CDSView(source=source, filters=[GroupFilter(column_name='item', group=list1[i])])
    p.line(x='x', 
           y='y',
           source=source,
           line_color=color[i],
           view=view,
           legend=list1[i],
           line_width=2
          )

hover=HoverTool(tooltips = [('Item', '@item'), ('X', '@x'), ('Y', '@y')], mode='mouse')

p.add_tools(hover)
p.legend.location = "top_right"
p.legend.title= "Item"

show(p)

Output enter image description here


Solution

  • As Eugene suggested, the inferno and viridis palettes go up to 256 colors, and by using an iterator you can automate the color choice.

    import numpy as np
    from bokeh.plotting import figure, output_file, show
    from bokeh.palettes import inferno# select a palette
    import itertools# itertools handles the cycling 
    
    numLines=50
    
    p = figure(width=800, height=400)
    x = np.linspace(0, numLines)
    
    colors = itertools.cycle(inferno(numLines))# create a color iterator 
    
    for m in range(numLines):
        y = m * x
        p.line(x, y, color=next(colors))
    
    show(p)
    

    The example is adjusted from When plotting with Bokeh, how do you automatically cycle through a color pallette?

    enter image description here