对于相同的数据,一些调色板会引发错误,而另一些则可以正常工作。
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”发挥作用?
最佳答案
显然,一些 Bokeh 调色板是列表,而另一些是字典。
print(type(Spectral6))
print(type(Dark2))
<class 'list'>
<class 'dict'>
Dark2 dict 实际上是一组调色板,由每个调色板中的颜色数量决定:
{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)
而列表类型调色板可以直接发送到“调色板”arg,只要它们至少包含与因子一样多的颜色。
factor_cmap('cats', palette=Spectral6, factors=factors)
关于python - 为什么一些 Bokeh 调色板在 factor_cmap() 中使用时会引发 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333820/