When plotting with Bokeh, how do you automatically cycle through a color pallette?

寵の児 提交于 2019-11-29 16:39:30

问题


I want to use a loop to load and/or modify data and plot the result within the loop using Bokeh (I am familiar with Matplotlib's axes.color_cycle). Here is a simple example

import numpy as np
from bokeh.plotting import figure, output_file, show
output_file('bokeh_cycle_colors.html')

p = figure(width=400, height=400)
x = np.linspace(0, 10)

for m in xrange(10):
    y = m * x
    p.line(x, y, legend='m = {}'.format(m))

p.legend.location='top_left'
show(p)

which generates this plot

How do I make it so the colors cycle without coding up a list of colors and a modulus operation to repeat when the number of colors runs out?

There was some discussion on GitHub related to this, issues 351 and 2201, but it is not clear how to make this work. The four hits I got when searching the documentation for cycle color did not actually contain the word cycle anywhere on the page.


回答1:


It is probably easiest to just get the list of colors and cycle it yourself using itertools:

import numpy as np
from bokeh.plotting import figure, output_file, show

# select a palette
from bokeh.palettes import Dark2_5 as palette
# itertools handles the cycling
import itertools  

output_file('bokeh_cycle_colors.html')

p = figure(width=400, height=400)
x = np.linspace(0, 10)

# create a color iterator
colors = itertools.cycle(palette)    

for m, color in zip(range(10), colors):
    y = m * x
    p.line(x, y, legend='m = {}'.format(m), color=color)

p.legend.location='top_left'
show(p)




回答2:


Two small changes will make prior answer work for Python 3.

  • changed: for m, color in zip(range(10), colors):

  • prior: for m, color in itertools.izip(xrange(10), colors):




回答3:


You can define a simple generator that cycles colors for you.

In python 3:

from bokeh.palettes import Category10
import itertools

def color_gen():
    yield from itertools.cycle(Category10[10])
color = color_gen()

or in python 2 (or 3):

from bokeh.palettes import Category10
import itertools

def color_gen():
    for c in itertools.cycle(Category10[10]):
        yield c
color = color_gen()

and when you need a new color, do:

p.line(x, y1, line_width=2, color=color)
p.line(x, y2, line_width=2, color=color)

Here is the above example:

p = figure(width=400, height=400)
x = np.linspace(0, 10)

for m, c in zip(range(10), color):
    y = m * x
    p.line(x, y, legend='m = {}'.format(m), color=c)

p.legend.location='top_left'
show(p)



来源:https://stackoverflow.com/questions/39839409/when-plotting-with-bokeh-how-do-you-automatically-cycle-through-a-color-pallett

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!