散景线图:绘制大量线条时如何分配颜色

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

我使用 for 循环(下面的代码)在 Bokeh 中创建了一个多线图。

在输出示例中只有两条曲线。在这种情况下,我可以为每条曲线设置一个颜色列表。但是,如果我需要绘制大量曲线,我该如何使用其中一个散景调色板(例如配对)?我想自动执行此操作,以避免每次增加要绘制的线条数时都必须制作颜色列表。

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)

输出

正如 Eugene 所建议的,inferno 和 viridis 调色板最多有 256 种颜色,通过使用迭代器,您可以自动选择颜色。

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)

示例调整自