Bokeh tutorial

1.2 Plotting - Timeseries

Exercise: Reproduce the timeseries chart using the plotting interface

  • Data: 'data/Land_Ocean_Monthly_Anomaly_Average.csv'

Note: Don't worry about styling right now. We'll go over plot properties in the next exercise


In [ ]:
import pandas as pd
from bokeh.plotting import figure, show, output_notebook

In [ ]:
# Get data
df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv')

In [ ]:
# Process data
df['datetime'] = pd.to_datetime(df['datetime'])
df = df[['anomaly','datetime']]
df['moving_average'] = pd.rolling_mean(df['anomaly'], 12)

In [ ]:
# Output option
output_notebook()

In [ ]:
# Create your plot
p = figure()
p.line(df['datetime'], df['anomaly'])
p.line(df['datetime'], df['moving_average'])

In [ ]:
# Show plot
show(p)

Exercise: Style the plot appropriately

Ideas:

  • Axis type and format
  • Line colors
  • Legend
  • Grid lines
  • Axis labels
  • Width and height
  • Remove toolbar

Tips:

bokeh.models.DatetimeTickFormatter()

Note: You can create a new figure to see observe the differences.


In [ ]:
from bokeh.models import DatetimeTickFormatter
import math

In [ ]:
# Axis type, width and height
t = figure(x_axis_type = "datetime", width=900, height=200)

In [ ]:
# Line colors and legend 
t.line(df['datetime'], df['anomaly'], color='lightgrey', legend='anom')
t.line(df['datetime'], df['moving_average'], color='red', legend='avg')

In [ ]:
# Axis format (e.g tick format and orientation)
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4

In [ ]:
# Axis labels
t.yaxis.axis_label = 'Anomaly(ºC)'

In [ ]:
# Legend position
t.legend.location = "bottom_right"

In [ ]:
# Grid style
t.grid.grid_line_alpha=0.2

In [ ]:
# Remove toolbar
t.toolbar_location=None

In [ ]:
# Show plot
show(t)

Exercise: Add a crosshair and hover tool to the plot


In [ ]:
from bokeh.models import ColumnDataSource, HoverTool
from collections import OrderedDict

In [ ]:
# List all the tools that you want in your plot separated by comas, all in one string.
TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"

In [ ]:
# Add the tools to your figure
t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

In [ ]:
# The hover tools doesn't render datetime appropriately. We'll need a string.
df["datetime_s"]=df[["datetime"]].applymap(str)

In [ ]:
# To reference variables in the hover box, we'll need to use bokeh.ColumnDataSource instead of a pd.DataFrame
source = ColumnDataSource(df)

In [ ]:
# Change plotting.line to get values from ColumnDataSource, name the renderer that you want to have the hover activated
t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

In [ ]:
# Set hover tool
hover = t.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
    ("anomaly", "@anomaly"),
    ("datetime", "@datetime_s"),
])
hover.renderers = t.select("mva")

In [ ]:
# Copy your style from the previous exercise
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4
t.yaxis.axis_label = 'Anomaly(ºC)'
t.legend.location = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None

In [ ]:
# Show plot
show(t)

[OPTIONAL] Exercise: Style the hover tooltip


In [ ]:
# New figure
t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

# Data processing
# The hover tools doesn't render datetime appropriately. We'll need a string. 
# We just want dates, remove time
f = lambda x: str(x)[:7]
df["datetime_s"]=df[["datetime"]].applymap(f)
source = ColumnDataSource(df)

# Create plot
t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

# Style
xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
t.xaxis[0].formatter = xformatter
t.xaxis.major_label_orientation = math.pi/4
t.yaxis.axis_label = 'Anomaly(ºC)'
t.legend.location = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None

# Style hover tool
hover = t.select(dict(type=HoverTool))
hover.tooltips = """
    <div>
        <span style="font-size: 15px;">Anomaly</span>
        <span style="font-size: 17px;  color: red;">@anomaly</span>
    </div>
    <div>
        <span style="font-size: 15px;">Month</span>
        <span style="font-size: 10px; color: grey;">@datetime_s</span>
    </div>
    """
hover.renderers = t.select("mva")

# Show plot
show(t)

In [ ]: