bokeh CategoricalColorMapper生成重复的图例

时间:2019-02-14 16:09:02

标签: python bokeh

我正在使用bokeh绘制不同类别​​的正方形。

然而,图例多次显示相同的类别,图中每个实例一次,而不是每个唯一类别一次。

这是重现我的问题的最少代码:

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, CategoricalColorMapper

ranges = [range(0, 100),
          range(100, 200),
          range(200, 300)]

cols = ['blue',
        'lime',
        'yellow']

labels = ['low',
          'medium',
          'high']

ranges_dict = dict(zip(ranges, labels))

lat = [0, 0, 100, 100]
lon = [0, 100, 0, 100]
values = [1, 150, 150, 250]

source = ColumnDataSource(dict(
        x=lon,
        y=lat,
        label=[[ranges_dict[r] for r in ranges if x in r] for x in values]
    ))

color_mapper = CategoricalColorMapper(factors=labels, palette=cols)

fig = figure(toolbar_location='below',
             width=500, height=400)

fig.rect(source=source,
         x='x', y='y',
         width=100,
         height=100,
         color={'field': 'label', 'transform': color_mapper},
         line_alpha=0.5, fill_alpha=0.5,
         legend='label'
         )

show(fig)

请注意,“中”出现了两次: bokeh output

1 个答案:

答案 0 :(得分:0)

问题是[[ranges_dict[r] for r in ranges if x in r] for x in values]返回列表列表: [['high'], ['medium'], ['low'], ['high']]

要将其转换为简单列表,我使用了 numpy.hstack ,因此ColumnDataSource的label参数应为以下形式: ['high', 'medium', 'low', 'high']