Skip to main content
 首页 » 编程设计

python之为点 Bokeh 添加标签

2025年05月04日19itcoder

根据他们的文档,我有以下内容:

album_names = ['Ctrl', 'Ctrl', 'Z', 'Ctrl', 'Ctrl', 'Z', 'Ctrl', 'Ctrl', 'Ctrl', 'Ctrl', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Ctrl', 'Ctrl', 'Ctrl', 'Ctrl', 'Ctrl', 'Ctrl', 'Z'] 
valence = [0.37, 0.598, 0.481, 0.166, 0.413, 0.0798, 0.549, 0.332, 0.348, 0.335, 0.355, 0.22, 0.433, 0.158, 0.357, 0.134, 0.367, 0.237, 0.248, 0.239, 0.535, 0.432, 0.505, 0.142] 
energy = [0.579, 0.686, 0.551, 0.367, 0.61, 0.475, 0.488, 0.525, 0.534, 0.517, 0.56, 0.342, 0.688, 0.505, 0.551, 0.63, 0.71, 0.453, 0.518, 0.708, 0.463, 0.684, 0.296, 0.576]` 
 
df = pd.DataFrame([album_names, energy, valence]).T 
df.columns = ['album_name', 'energy', 'valence'] 

我想使用 Bokeh 绘制散点图,x 轴为化合价,y 轴为能量。此外,当您将鼠标悬停在每个点上时,我希望它说出它对 album_name 的值(value)。并且点的颜色是基于album_name。

我尝试了以下方法:

from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label 
from bokeh.io import output_notebook, show 
from bokeh.plotting import figure 
from bokeh.palettes import brewer 
 
source = ColumnDataSource(data=dict(valence=valence, 
                                    energy=energy, 
                                    names=album_names)) 
 
p = figure() 
p.scatter(x='valence', y='energy', size=8, source=source) 
labels = LabelSet(x='valence', y='energy', text='names', 
                  level='glyph', x_offset=5, y_offset=5, 
                  source=source, render_mode='canvas') 
 
p.add_layout(labels) 
show(p) 

但是当您将鼠标悬停在该点上时,这不会显示相册名称。它修复了点旁边的专辑名称。非常感谢仅在将鼠标悬停在该点上并根据 album_name 的值更改颜色时让 album_name 显示的任何帮助

注:类似下图

请您参考如下方法:

检查它就可以了:

from bokeh.plotting import figure, ColumnDataSource, output_notebook, show 
from bokeh.models import HoverTool, WheelZoomTool, PanTool, BoxZoomTool, ResetTool, TapTool, SaveTool 
from bokeh.palettes import brewer 
 
output_notebook() 
 
#preprocessing the data with column album_name 
category = 'album_name' 
 
category_items = df[category].unique() 
#selecting the colors for each unique category in album_name 
palette = brewer['Set2'][len(category_items) + 1] 
#mapping each category with a color of Set2 
colormap = dict(zip(category_items, palette)) 
#making a color column based on album_name 
df['color'] = df[category].map(colormap) 
 
title = "Album_names" 
#feeding data into ColumnDataSource 
source = ColumnDataSource(df) 
#Editing the hover that need to displayed while hovering 
hover = HoverTool(tooltips=[('Album_name', '@album_name')]) 
#tools that are need to explote data 
tools = [hover, WheelZoomTool(), PanTool(), BoxZoomTool(), ResetTool(), SaveTool()] 
 
#finally making figure with scatter plot 
p = figure(tools=tools,title=title,plot_width=700,plot_height=400,toolbar_location='right',toolbar_sticky=False, ) 
p.scatter(x='valence',y='energy',source=source,size=10,color='color',legend=category) 
 
#displaying the graph 
show(p) 

输出将显示为 album_name Ctrl 输出将显示为 album_name Z 。