Last active
May 23, 2020 14:27
-
-
Save 23pointsNorth/0023d0fb0d209e236c5b2ff2b2c67b95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is based on code examples here | |
# https://docs.bokeh.org/en/latest/docs/user_guide/tools.html | |
# And has been modified to be abstracted better. | |
import json | |
from pathlib import Path | |
import numpy as np | |
from bokeh.embed import json_item | |
from bokeh.io import output_file, show | |
from bokeh.models import ColumnDataSource, HoverTool | |
from bokeh.plotting import figure | |
from bokeh.sampledata.stocks import AAPL | |
def main(viz_type="web"): | |
def datetime(x): | |
return np.array(x, dtype=np.datetime64) | |
source = ColumnDataSource( | |
data={ | |
"date": datetime(AAPL["date"][::10]), | |
"adj close": AAPL["adj_close"][::10], | |
"volume": AAPL["volume"][::10], | |
"extra_data": list(range(len(AAPL["volume"][::10]))), | |
} | |
) | |
p = figure( | |
plot_height=250, | |
x_axis_type="datetime", | |
tools="pan,wheel_zoom,box_zoom,reset,save", | |
toolbar_location="below", | |
title="AAPL price with Tooltip", | |
sizing_mode="scale_width", | |
output_backend="svg", | |
) | |
p.toolbar.logo = None | |
p.background_fill_color = "#f5f5f5" | |
p.grid.grid_line_color = "white" | |
p.xaxis.axis_label = "Date" | |
p.yaxis.axis_label = "Price" | |
p.axis.axis_line_color = None | |
p.line(x="date", y="adj close", line_width=2, color="#ebbd5b", source=source) | |
p.add_tools( | |
HoverTool( | |
tooltips=[ | |
# use @{ } for field names with spaces | |
("date", "@date{%F}"), | |
("close", "$@{adj close}{%0.2f}"), | |
("volume", "@volume{0.00 a}"), | |
("extra_data", "@extra_data"), | |
("extra_note", "just any value"), | |
], | |
formatters={ | |
"@date": "datetime", # use 'datetime' formatter for 'date' field | |
"@{adj close}": "printf", # use 'printf' formatter for 'adj close' field | |
# use default 'numeral' formatter for other fields | |
}, | |
# display a tooltip whenever the cursor is vertically in line with a glyph | |
mode="vline", | |
) | |
) | |
if viz_type == "web": | |
# Make the outputfile the same name as this script | |
filename = Path(__file__).stem + ".html" | |
output_file(filename) | |
show(p) | |
elif viz_type == "json": | |
# Make the outputfile the same name as this script | |
filename = Path(__file__).stem + ".json" | |
with open(filename, "w") as json_file: | |
div_id = "example_plot_With_hover" | |
json.dump(json_item(p, div_id), json_file) | |
else: | |
print("Unsupported viz_type. What did you really want to say?") | |
if __name__ == "__main__": | |
main() | |
main(viz_type="json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment