Python >> Tutoriel Python >  >> Python Tag >> Bokeh

Lorsque vous tracez avec Bokeh, comment parcourez-vous automatiquement une palette de couleurs ?

Il est probablement plus simple d'obtenir la liste des couleurs et de la parcourir vous-même en utilisant 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)


Deux petits changements feront fonctionner la réponse précédente pour Python 3.

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

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


Vous pouvez définir un générateur simple qui cycle les couleurs pour vous.

En python 3 :

from bokeh.palettes import Category10
import itertools

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

ou en python 2 (ou 3) :

from bokeh.palettes import Category10
import itertools

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

et quand vous avez besoin d'une nouvelle couleur, faites :

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

Voici l'exemple ci-dessus :

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)