Skip to content

Instantly share code, notes, and snippets.

@karenyyng
Last active September 10, 2018 20:29
Show Gist options
  • Save karenyyng/331a4a573a24dc33995fe528e8882f5a to your computer and use it in GitHub Desktop.
Save karenyyng/331a4a573a24dc33995fe528e8882f5a to your computer and use it in GitHub Desktop.
bokeh_cheatsheet

making simple plot

to show plot within Jupyter notebook

execute this following line at the top of the notebook

output_notebook()
from bokeh.io import output_notebook, output_file
from bokeh.plotting import figure, show, ColumnDataSource

x_values = [1, 2, 3, 4, 5]
y_values = [6, 7, 2, 3, 6]

p = figure(width=800, height=600, title='TITLE OF THE PLOT')
p.circle(x=x_values, y=y_values, legend='to appear on the legend')
p.legend.location = "center_right"
p.legend.background_fill_color = "darkgrey"
p.xaxis.axis_label = 'x'
p.yaxis.axis_label = 'Pr(x)'

show(p)

use ColumnDataSource

such as dataframes

from bokeh.models import HoverTools
data = {'x_values': [1, 2, 3, 4, 5],
        'y_values': [6, 7, 2, 3, 6]}

source = ColumnDataSource(data=data)

# use `@` to retrieve the column values from a dataframe
# use `$x` to retrieve the x value of the plotted point
hover = HoverTool(tooltips=[
    ("(x, y)", "(@x_values, @y_values)"),
    ("x", "$x{0}")  # this `{0}` will make sure that the hover values are integers with 0 decimial points
])
p = figure(tools=[hover, 'pan', 'save', 'box_zoom'])
p.circle(x='x_values', y='y_values', source=source, )

show(p)

ref for using HoverTool ref for other tools specify the default tool by their names as strings

ref to make sure hovertools show integers for numerical values

adding legend to plot with specific location

ref

r0 = p.line(x, y, source=source)
r1 = p.line(x1, y1, source=source)
r2 = p.line(x2, y2, source=source)
r3 = p.line(x3, y3, source=source)
legend = Legend(items=[
    ("sin(x)",   [r0, r1]),
    ("2*sin(x)", [r2]),
    ("3*sin(x)", [r3,])
], location=(0, -30))

p.add_layout(legend, 'right')

saving the plot to html

Just add the following line

output_file('histogram.html', title="histogram.py example")

bokeh modules / objects to import

from bokeh.io import output_notebook
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.models import HoverTool, Legend

arrange plots in a layout with widgets

ref

from bokeh.layouts import column, row, gridplot, widgetbox
from bokeh.models.widgets import Button, RadioButtonGroup, Select, Slider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment