Skip to main content
 首页 » 编程设计

python之ColumnDataSource 中的 Bokeh 圆图颜色

2024年12月31日11xing901022

我正在尝试使用 Bokeh 在交互式圆图中显示我的集群。我设法显示了绘图本身,但图表上的所有规范都是蓝色的。我想在 4 个集群中显示它们,因为这是一个集群分析。

这是在没有实现颜色的情况下工作的代码:

colormap = {0: 'brown', 1: 'green', 2: 'blue', 3: 'purple'} 
colors = [colormap[x] for x in df['cluster']] 
 
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) 
 
p.add_tools(hover) 
 
 
 
output_file("sentiment.html", title="sentiment.py example") 
 
show(p) 

在 p.circle 中添加颜色属性 color=colors 时,出现错误,因为我需要在 source = ColumnDataSource( data=df).

有谁知道如何在 ColumnDataSource 中实现这个 colors 属性?

请您参考如下方法:

创建一个 values:colors 字典,然后在您的数据框中创建一个新列。这是一个简化的示例:

df = pd.DataFrame(data={"col1":[0, 1, 2, 3, 1, 2, 3]}) 
colors =  {0: "brown", 1: "green", 2: "blue", 3: "purple"} 
df["color"] = df["col1"].apply(lambda c: colors[c])