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

如何在Bokeh工具提示中为数值添加单位(如tonnes、HP)

在Bokeh图表悬停提示中为数值添加单位的方法

需求说明

希望在Bokeh图表的悬停提示中为重量和马力数值添加对应单位,期望显示格式如下:

Model: plymouth fury
Weight: 3785 tonnes
HP: 95 HP

原代码

from bokeh.plotting import figure, output_notebook, show, row
from bokeh.models import ColumnDataSource as cds

output_notebook()
import seaborn as sns

mpg = sns.load_dataset('mpg')

usa = mpg[mpg.origin == 'usa']
japan = mpg[mpg.origin == 'japan']
europe = mpg[mpg.origin == 'europe']

sourceU = cds(data=usa)
sourceJ = cds(data=japan)
sourceE = cds(data=europe)

tt = [('Model','@name'),('Weight','@weight'),('HP','@horsepower')]
# 需要修改此行来添加单位字符串

fig1 = figure(x_axis_label = 'Weight',y_axis_label='HP',width=350,height=300,title="USA",tooltips=tt)
fig2 = figure(x_axis_label = 'Weight',y_axis_label='HP',width=350,height=300,title="Japan",tooltips=tt)
fig3 = figure(x_axis_label = 'Weight',y_axis_label='HP',width=350,height=300,title="Europe",tooltips=tt)

fig1.circle(x='weight',y='horsepower',source=sourceU)
fig2.circle(x='weight',y='horsepower',source=sourceJ)
fig3.circle(x='weight',y='horsepower',source=sourceE)

show(row(fig1,fig2,fig3))

修改方法

直接在tooltip的字段模板中拼接单位字符串,Bokeh支持在模板中嵌入HTML标签实现样式效果。将原tooltip定义行替换为:

tt = [
    ('Model', '@name'),
    ('Weight', '@weight <strong>tonnes</strong>'),
    ('HP', '@horsepower <strong>HP</strong>')
]

说明

  • 每个元组的第二个元素是提示文本的模板,@weight和@horsepower会被数据源中的对应数值替换
  • 拼接的<strong>标签可以让单位文本加粗,符合期望的显示格式
  • 无需修改其他代码,替换后重新运行即可看到带单位的悬停提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:20:21