bokeh CategoricalColorMapper生成重复的图例

问题描述 投票:0回答:1

我正在使用散景来绘制不同类别​​的方块。

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

这是一个重现我的问题的最小代码:

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)

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

python bokeh
1个回答
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']

© www.soinside.com 2019 - 2024. All rights reserved.