python - Bokeh 线图 : How to assign colors when plotting a large number of lines

标签 python bokeh palette line-plot

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

在输出示例中只有两条曲线。在这种情况下,我可以为每条曲线设置一个颜色列表。但是,如果我需要绘制大量曲线,我该如何使用其中一个 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)

输出 enter image description here

最佳答案

正如 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)

示例调整自When plotting with Bokeh, how do you automatically cycle through a color pallette?

enter image description here

关于python - Bokeh 线图 : How to assign colors when plotting a large number of lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64545717/

相关文章:

python - 使用用户输入作为正则表达式搜索表达式

python - Bokeh session 和文档轮询

delphi - 如何访问 TPicture.Graphic 的调色板?

Android 调色板不起作用?

eclipse - 将 Richfaces 添加到 Eclipse Palette?

python - 处理异常和继续的问题

python pandas groupby() 结果

python - 如何在 PyQt4 中创建多页应用程序?

python - 使用特定列填充 Bokeh 中的工具提示

python - 如何使用 Bokeh 获取 pandas 时间序列数据框的条形图?