为什么在使用factor_cmap()时,部分bokeh调色板会引发ValueError错误?

4

使用相同的数据,有些调色板会出错,而有些则可以正常工作。

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

这个可以正常工作,
p = figure()
p.circle('x', 'y', size=10,
         color=factor_cmap('cats', palette=Spectral6, factors=factors), 
         source=source)
show(p)

这个会返回一个错误:

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']}

这些调色板有什么区别,我们如何使用“Dark2”调色板?
1个回答

5
显然,有些bokeh调色板是列表,而其他一些是字典。
print(type(Spectral6))
print(type(Dark2))

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

Dark2字典实际上是一组调色板,按每个调色板中颜色的数量进行键分组:
{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']}

所以它需要像这样使用:
pal = Dark2[3]
factor_cmap('cats', palette=pal, factors=factors)

如果清单类型的调色板包含的颜色数量至少与因素数量相同,则可以将其直接发送到“palette”参数。

factor_cmap('cats', palette=Spectral6, factors=factors)

1
所有调色板都可以通过唯一的名称访问,例如在这种情况下 Dark2_3 也可以使用。但是,调色板组也被收集到字典中,因为有时按调色板大小索引某些内容很方便。 - bigreddot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接