I have a pandas DataFrame:
I A A2 B B2
1 'dog' 10 'cat' 20
2 'elf' 15 'egg' 45
3 'hat' 80 'bag' 50
I have then converted this into a Bokeh DataTable but have only included columns I, A and B.
I'd like to add a tooltip for the cells in columns A and B and to show the corresponding value in A2 or B2. So, for example if you were hovering over 'dog', the tooltip would be 10 and if you hovered over 'bag' the tooltip would be 50.
From what I understand, there isn't (yet) a way to add a tooltip using HoverTool, which can be done on scatter plots etc. But this answer suggests a workaround is possible, although in that example the tooltip shows only the value already displayed in the table. How would I get the tooltip to show the corresponding value instead?
The HTMLTemplateFormatter class is an HTML formatter that uses a template string passed to it as a kwarg
. It uses the template method and syntax in Undescorejs to render the template. The syntax allows if-else conditional rendering of the template and allows one to use values from other columns by directly passing the column names in the template. We will use this information to define our template based on the condition specified in your question, i.e., get tooltip title from adjacent column if columns are A and B.
Note: The values in my dataframe were without the inverted commas (' '). For instance, I had dog
instead of 'dog'
. The DataTable looks neater without them :).
The code below is inspired by the linked answer in your question and performs the following steps:
df2
,source
,template
,Columns
with HTMLTemplateFormatter
for TableColumn
rendering with template
,data_table
,data_table
.Code:
Notice the template
string uses conditional statements with column names used directly for comparison, rendering of the tooltip title and row values.
import pandas as pd
from bokeh.models.widgets import DataTable, TableColumn, HTMLTemplateFormatter
from bokeh.models import ColumnDataSource
from bokeh.io import show
df2 = pd.read_csv('bokeh.csv')
source = ColumnDataSource(df2)
template = """<% if (value==A) {%>
<span href="#" data-toggle="tooltip" title="<%= A2 %>"><%= value %></span>
<%}
else if (value==B){%>
<span href="#" data-toggle="tooltip" title="<%= B2 %>"><%= value %></span>
<%}
else {%>
<span href="#"><%= value %></span>
<%}%>"""
Columns = [TableColumn(field=Ci, title=Ci, width=20, formatter=HTMLTemplateFormatter(template=template)) for Ci in df2.columns]
data_table = DataTable(source=source, columns=Columns, width=400, height=280)
show(data_table)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With