Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some bokeh palettes raise a ValueError when used in factor_cmap()

With the same data, some palettes raise an error and some just work.

from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.transform import factor_cmap
from bokeh.palettes import Spectral6, Dark2

output_file("colormapped_dots.html")

cats = ['A', 'A', 'B', 'B', 'C', 'C']
x = [5, 3, 4, 2, 4, 6]
y = x
factors = list(set(cats))
source = ColumnDataSource(data=dict(cats=cats, x=x, y=y))

This one works,

p = figure()
p.circle('x', 'y', size=10,
         color=factor_cmap('cats', palette=Spectral6, factors=factors), 
         source=source)
show(p)

This one returns an error,

p = figure()
p.circle('x', 'y', size=10,
         color=factor_cmap('cats', palette=Dark2, factors=factors), 
         source=source)
show(p)


ValueError: expected an element of Seq(Color), got {3: ['#1b9e77', '#d95f02', '#7570b3'], 4: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a'], 5: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e'], 6: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02'], 7: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d'], 8: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666']}

What's the difference between these palettes and how do we get 'Dark2' to work?

like image 245
davemfish Avatar asked Oct 27 '25 19:10

davemfish


1 Answers

Apparently some bokeh palettes are lists and others are dicts.

print(type(Spectral6))
print(type(Dark2))

<class 'list'>
<class 'dict'>

The Dark2 dict is really a set of palettes, keyed by the number of colors in each palette:

{3: ['#1b9e77', '#d95f02', '#7570b3'],
 4: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a'],
 5: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e'],
 6: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02'],
 7: ['#1b9e77',
  '#d95f02',
  '#7570b3',
  '#e7298a',
  '#66a61e',
  '#e6ab02',
  '#a6761d'],
 8: ['#1b9e77',
  '#d95f02',
  '#7570b3',
  '#e7298a',
  '#66a61e',
  '#e6ab02',
  '#a6761d',
  '#666666']}

So it needs to be used like this:

pal = Dark2[3]
factor_cmap('cats', palette=pal, factors=factors)

Whereas the list type palettes can be sent straight to the 'palette' arg, as long as they contain at least as many colors as there are factors.

factor_cmap('cats', palette=Spectral6, factors=factors)
like image 68
davemfish Avatar answered Oct 30 '25 09:10

davemfish