python - Bokeh 上出现重复的图例标签

标签 python bokeh

我正在尝试使用圆环图和 bokeh 库来显示定性数据。我有 2 个数据集共享一些数据标签,并且我想要一个统一的图例来收集这两个标签。

我已经设法只显示一个图的图例,或者同时显示两个图的图例,但包含重复的项目。但是,我没有找到一种方法来拥有独特的条目。这是显示我的问题的示例代码:

from math import pi
import pandas as pd
from bokeh.io import show
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.palettes import Set3

# Create fake data
df = pd.DataFrame(
    {'label': ['X{}'.format(i) for i in range(0, 4)] + ['X{}'.format(i) for i in range(2, 8)],
     'angle': [2*pi / 4] * 4 + [2*pi / 6] * 6,
     'group': [1]*4 + [2]*6})

# Set up colors
unique_labels = df.label.unique()
color_mapping = pd.Series(dict(zip(unique_labels, Set3[len(unique_labels)])))
df['color'] = color_mapping.loc[df.label].values

# Plot two concentric donuts
p = figure(title='Test', tools="hover", tooltips="@label")

p.annular_wedge(source=df[df.group==1], x=0, y=1, inner_radius=0.5, outer_radius=0.6,
                start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
                line_color="white", fill_color='color', legend_group='label')

p.annular_wedge(source=df[df.group==2], x=0, y=1, inner_radius=0.3, outer_radius=0.4,
                start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
                line_color="white", fill_color='color', legend_group='label')
show(p)

最后,我得到以下结果:

enter image description here

有办法解决吗? 我发现了其他相关问题(即 matplotlib),但不适用于 Bokeh 。

最佳答案

我认为这会起作用:

legend_tmp = {x.label['value']: x for x in p.legend.items}
p.legend.items.clear()
p.legend.items.extend(legend_tmp.values())

当它为绘图创建图例时,它会添加两个 angular_wedge 的所有项目,但它不会按照您期望的方式进行重复数据删除,因为图例成员相当复杂的对象本身(意味着它们不仅仅是通过标签的值来识别的)。

关于python - Bokeh 上出现重复的图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59976804/

相关文章:

python - 多选下拉菜单 Bokeh

javascript - 用于小部件的 Python Bokeh CustomJS

python - 在 Bokeh 中使用自定义 html 工具提示时如何抑制科学计数法?

bar-chart - Bokeh - 堆叠和分组图表

python - Web 应用程序 : Hold large object between requests

python - 我在哪里可以找到包含常见食物列表的文本列表或图书馆?

python - 填补 Pandas 数据框中缺失的日子

python - python 中 string.partition 的良好实践

python - 设置seaborn/matplotlib始终使用edgecolor ='k'参数

python - 中心嵌入 Bokeh 图