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

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']


我想使用散景绘制散点图,其中在x轴上具有化合价,在y轴上具有能量。另外,当您将鼠标悬停在每个点上时,我要说的是album_name的值。点的颜色基于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)


但是,当您将鼠标悬停在该点上时,这不会显示专辑名称。它将专辑名称固定在该点旁边。非常感谢您提供任何帮助,以便仅将鼠标悬停在该点上时才显示专辑名称,并根据专辑名称的值更改颜色

注意:它类似于下面
python - 为点散景添加标签-LMLPHP

最佳答案

选中它可以解决问题:

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 python - 为点散景添加标签-LMLPHP所示
输出将显示为如Album_name Z python - 为点散景添加标签-LMLPHP所示

10-07 15:16