Interactive Bokeh Legends
Table of Contents
Introduction
This is a reproduction of the bokeh interactive legends example.
Set Up
Imports
Python
I have a class that I use to embed the bokeh and I'm going to make it easier to reuse by binding some values to it with partial.
from functools import partial
PyPi
- Bokeh
The
Spectral
color scheme from bokeh.palettes is a categorical color scheme from Color Brewer, a color scheme helper for cartographers.from bokeh.palettes import Spectral4 from bokeh.plotting import figure from bokeh.sampledata.stocks import AAPL, IBM, MSFT, GOOG
- Pandas And HoloViews
Pandas is for the data, holoviews is because I created the EmbedBokeh class expecting to always use it..
import holoviews import pandas
My Stuff
This is a convenience class for embedding the javascript that bokeh creates into this post.
from bartleby_the_penguin.tangles.embed_bokeh import EmbedBokeh
The Embedder
The files_path
is where the javascript needs to be stored for nikola
to copy it to the right place.
files_path = Path("../../files/posts/libraries/interactive-bokeh-legends/")
Embed = partial(
EmbedBokeh,
folder_path=files_path)
The Bokeh Backend
For some reason the backend is defaulting to matplotlib
so this fixes it.
holoviews.extension("bokeh")
Hide Plots
This creates a plot where the entry fore each line in the legend becomes a button that toggles the plot's visibility.
plot = figure(plot_width=800, plot_height=400,
x_axis_type="datetime",
tools="hover,pan,wheel_zoom,box_zoom,reset")
plot.title.text = "Some Stock Prices (Click On the Legend To Hide Plots)"
for data, name, color in zip([AAPL, IBM, MSFT, GOOG], "Apple IBM Microsoft Google".split(), Spectral4):
frame = pandas.DataFrame(data)
frame["date"] = pandas.to_datetime(frame["date"])
plot.line(frame["date"], frame["close"], line_width=2, color=color, alpha=0.8, legend=name)
plot.legend.location = "top_left"
plot.legend.click_policy = "hide"
plot.title.text_font_size = "14pt"
Output The Plot
Fade Plots
Clicking on the line in the legend will change the alpha-value for the line (to make it less visible). This has the effect of keeping the hovertool working for the line, while hiding it disables the hover tool.
fade_plot = figure(plot_width=800, plot_height=400,
x_axis_type="datetime",
tools="hover,pan,wheel_zoom,box_zoom,reset")
fade_plot.title.text = "Some Stock Prices (Click On the Legend To Mute Plots)"
fade_plot.title.text_font_size = "14pt"
for data, name, color in zip([AAPL, IBM, MSFT, GOOG], "Apple IBM Microsoft Google".split(), Spectral4):
frame = pandas.DataFrame(data)
frame["date"] = pandas.to_datetime(frame["date"])
fade_plot.line(frame["date"], frame["close"], line_width=2, color=color, muted_alpha=0.2, muted_color=color, alpha=0.8, legend=name)
fade_plot.legend.location = "top_left"
fade_plot.legend.click_policy = "mute"