The result is:
This code how to generate interactive figure with several 1D plot, one hovertools and togglable legend using Python and Bokeh. This is a continuing post of last one.
See also:
Python Matplotlib Tips: Interactive 1D time-scale plot with hovertool using Python and Bokeh
This page shows how to generate interactive time-scale 1D line plot with hovertool (stock data) using Python and Bokeh.
In [1]:
import datetime
import platform
print('python: '+platform.python_version())
import numpy as np
print('numpy: '+np.__version__)
Define x and y value
In [2]:
numdays = 2000
xs = range(0, numdays)
ys1 = np.sin(np.linspace(0,10*np.pi,numdays))
ys2 = np.sin(np.linspace(0,10*np.pi,numdays)+2*np.pi/3)
ys3 = np.sin(np.linspace(0,10*np.pi,numdays)+4*np.pi/3)
Load bokeh and enable notebook connection
In [3]:
from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook
from bokeh.models import HoverTool, ColumnDataSource
output_notebook()
Generate interactive plot
In [4]:
# define figure
p = figure(x_axis_label='Time', y_axis_label='Value',
plot_width=600, plot_height=300)
source = ColumnDataSource(data={
'xsdata' : xs,
'y1data' : ys1,
'y2data' : ys2,
'y3data' : ys3,
})
# plot a line to the figure
l1 = p.line('xsdata', 'y1data', source=source, alpha=1.0,
muted_alpha=0.2,line_width=2, legend='y1label', color='red')
l2 = p.line('xsdata', 'y2data', source=source, alpha=1.0,
muted_alpha=0.2, line_width=2, legend='y2label', color='green')
l3 = p.line('xsdata', 'y3data', source=source, alpha=1.0,
muted_alpha=0.2, line_width=2, legend='y3label', color='blue')
# add hover tools to the figure
p.add_tools(HoverTool(
renderers=[l1],
# you can see the detail of the formatter at:
# https://bokeh.pydata.org/en/latest/docs/reference/models/formatters.html
tooltips=[('Time','@xsdata'),
('u', '@y1data{+0.00}'),
('v', '@y2data{+0.00}'),
('w', '@y3data{+0.00}'),],
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline'
))
# draw legend
p.legend.location = "top_left"
p.legend.click_policy="mute"
# display the figure in the notebook
show(p)