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

如何在Bokeh的ColumnDataSource中设置散点图聚类颜色?

How to Add Cluster-Based Color Mapping to ColumnDataSource in Bokeh

我之前也碰到过一模一样的问题,其实解决起来很简单——你只需要把生成的颜色列表整合到数据源里,让Bokeh可以直接从ColumnDataSource读取颜色信息就行,具体操作如下:

问题原因

你直接在p.circle里传入color=colors报错,是因为当指定了source参数后,Bokeh要求所有可视化属性(包括颜色)都从这个统一的数据源中获取,这样才能保证数据与视觉元素的绑定一致性,支持后续的交互操作。

修改后的完整可运行代码

from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, HoverTool

# 假设你的df已包含cluster列
colormap = {0: 'brown', 1: 'green', 2: 'blue', 3: 'purple'} 
colors = [colormap[x] for x in df['cluster']]

# 把颜色列表添加为DataFrame的新列
df['point_color'] = colors

# 创建包含颜色字段的ColumnDataSource
source = ColumnDataSource(data=df) 

hover = HoverTool(tooltips=[
    ('index', '@index'),
    ('Tweets','@Bericht'), 
    ('Polarity','@Polarity'), 
    ('Subjectivity','@Subjectivity')
]) 

p = figure(title = "Sentiment analyse", plot_width=1000, plot_height=500) 
p.xaxis.axis_label = 'Polarity' 
p.yaxis.axis_label = 'Subjectivity' 

# 从数据源中引用颜色字段
p.circle(x='Polarity', y='Subjectivity', source=source, 
         fill_alpha=0.2, size=6, color='point_color') 

p.add_tools(hover) 
output_file("sentiment.html", title="sentiment.py example") 
show(p)

关键步骤说明

  1. 整合颜色到DataFrame:通过df['point_color'] = colors把每个数据点对应的颜色添加为DataFrame的一列,让数据源包含完整的视觉映射信息。
  2. 在图形元素中引用数据源字段:在p.circle里设置color='point_color',这里的字符串对应ColumnDataSource中的字段名,Bokeh会自动为每个数据点匹配对应的聚类颜色。

这样修改后,你的散点图就会按聚类结果显示不同颜色,同时完全保留原来的交互功能!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:58:28