I would like to create a categorial scatter plot with these functions using bokeh:
Hover Tooltips
Legend outside the plot area with click policy = "hide"
After numerous searches, I can implement the function #1 and #2 separately.
But I don't know how to make these 2 functions work at the same time.
Tooltips only needs one glyph object, but legend outside plot area needs a for-loop to create a list of glyph objects which is used to generate legend_items.
Thanks.
Code Example:
- Hover Tooltips can be achieved by using ColumnDataSources (https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#heat-maps)
import pandas as pd
from bokeh.sampledata.stocks import AAPL
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show
df = pd.DataFrame(AAPL)
output_file("test.html")
p = figure(tools="hover")
source = ColumnDataSource(df)
p.scatter("high", "low", source=source)
p.hover.tooltips = [("Date","@date")]
show(p)
- Legend outside the plot (Position the legend outside the plot area with Bokeh)
import pandas as pd
from bokeh.models import Legend, LegendItem
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT
output_file("test2.html")
p = figure(x_axis_type="datetime")
p_list = []
for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
p_list.append(p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8))
legend_items = [LegendItem(label=x, renderers=[p_list[i]]) for i, x in enumerate(["AAPL", "IBM", "MSFT", "GOOG"])]
legend_ = Legend(items=legend_items, click_policy="hide", location="center", label_text_font_size="12px")
p.add_layout(legend_, "right")
show(p)