You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用color_mapper的Bokeh分类图如何实现按类别单独隐藏图形元素

问题原因

你当前的写法无法实现单个类别隐藏的核心原因是:使用legend_field参数时,所有分类的散点都属于同一个GlyphRenderer对象,图例上的多个分类条目只是逻辑分组,实际全部绑定同一个渲染器,点击任意条目都会触发整个渲染器的隐藏/显示,自然会一次性隐藏所有点。

解决方案

这个需求无法仅通过color_mapper实现,需要按类别拆分数据,单独绘制每个分类的glyph才能实现单独控制显隐的效果,参考代码如下:

from bokeh.models import ColumnDataSource
from bokeh.palettes import Category10_3
from bokeh.plotting import figure

category = ['cat1', 'cat2', 'cat3']
palette = Category10_3
        
plot = figure(
    x_range=(-x_range, x_range),
    y_range=(y_range[0], y_range[1]),
    title=title,
    width=500,
    height=800,
    tools=TOOLS
)

# 遍历每个类别单独渲染
for idx, cat in enumerate(category):
    # 筛选当前类别的子集数据
    cat_data = df[df['category'] == cat]
    cat_source = ColumnDataSource(cat_data)
    plot.circle(
        x='x', 
        y='y',
        size=8, 
        source=cat_source, 
        color=palette[idx],
        legend_label=cat
    ) 

plot.legend.click_policy='hide'

该写法下每个分类对应独立的渲染器,图例条目和渲染器一一绑定,点击单个分类图例即可仅隐藏对应类别的散点。

内容的提问来源于stack exchange,提问作者Maxi Trien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:06:03