Last modified: Jan 02, 2025 By Alexander Williams
Python Bokeh HoverTool: Add Interactive Tooltips Guide
The HoverTool()
in Bokeh is a powerful feature that adds interactive tooltips to your plots, making them more informative and engaging. Let's explore how to implement and customize hover tooltips in Bokeh.
Basic HoverTool Implementation
First, let's create a simple scatter plot with basic hover tooltips. We'll use ColumnDataSource
to organize our data, which makes it easier to reference in the hover tooltips.
from bokeh.plotting import figure, show
from bokeh.models import HoverTool, ColumnDataSource
import numpy as np
# Create sample data
x = np.random.rand(50) * 100
y = np.random.rand(50) * 100
source = ColumnDataSource(data=dict(
x=x,
y=y,
size=np.random.rand(50) * 20
))
# Create figure
p = figure(width=600, height=400, title="Basic Hover Example")
# Add circle glyphs
p.circle('x', 'y', size='size', source=source)
# Add hover tool
hover = HoverTool(tooltips=[
('X-Coordinate', '@x{0.2f}'),
('Y-Coordinate', '@y{0.2f}'),
('Size', '@size{0.2f}')
])
p.add_tools(hover)
show(p)
Customizing Tooltip Format
You can customize the appearance and format of tooltips using HTML formatting and special field formatters. Here's how to create more sophisticated tooltips.
from bokeh.models import HoverTool
from bokeh.plotting import figure, show
import pandas as pd
# Create sample data
data = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=30),
'value': np.random.randn(30).cumsum(),
'category': ['A' if i < 15 else 'B' for i in range(30)]
})
source = ColumnDataSource(data)
p = figure(width=700, height=400, title="Advanced Hover Example")
p.line('date', 'value', source=source)
# Create custom HTML tooltip
hover = HoverTool(tooltips="""
Data Point Info
Date: @date{%F}
Value: @value{0.00}
Category: @category
""", formatters={"@date": "datetime"})
p.add_tools(hover)
show(p)
Using Mode Property
The mode property determines how the hover tool behaves. You can set it to 'mouse' (default), 'vline', or 'hline' for different interaction styles.
# Create hover tool with vline mode
hover = HoverTool(
tooltips=[
('Value', '@value{0.00}'),
('Date', '@date{%F}')
],
formatters={"@date": "datetime"},
mode='vline' # Shows a vertical line at mouse position
)
p = figure(width=600, height=400, title="Vertical Line Hover")
p.line('date', 'value', source=source)
p.add_tools(hover)
show(p)
Conditional Tooltips
You can create conditional tooltips that change based on data values using JavaScript callbacks. Here's an example that changes tooltip colors based on values.
from bokeh.models import CustomJS
hover = HoverTool(tooltips="""
Value: @value{0.00}
Status: <%= value > 0 ? 'Positive' : 'Negative' %>
""")
Integration with Other Tools
HoverTool works seamlessly with other Bokeh features. You can combine it with ColumnDataSource for complex data handling and gridplot for multi-plot layouts.
Best Practices
Keep tooltips concise and relevant to your data visualization. Use formatting to improve readability, and consider mobile users when designing tooltip layouts.
Test your tooltips with different screen sizes and data values to ensure they remain readable and useful in all scenarios.
Common Issues and Solutions
If tooltips don't appear, verify that your ColumnDataSource
column names match the tooltip references. Use the '@' prefix for data columns and '$' for special variables.
Conclusion
The HoverTool is an essential feature for creating interactive Bokeh visualizations. By mastering its features, you can create more engaging and informative data visualizations.
Remember to balance interactivity with performance, and always consider your users' needs when designing tooltip content and formatting.