如何在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
相关产品推荐
相关产品推荐

