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 [1]:
import pandas as pd
from bokeh.plotting import figure, show, output_notebook

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

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

In [4]:
# Output option
output_notebook()


BokehJS successfully loaded.

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


Out[5]:
<bokeh.plotting.Figure at 0x109179190>

In [6]:
# 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 [7]:
from bokeh.models import DatetimeTickFormatter
import math

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

In [9]:
# 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')


Out[9]:
<bokeh.plotting.Figure at 0x109136550>

In [10]:
# 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 [11]:
# Axis labels
t.yaxis.axis_label = 'Anomaly(ºC)'

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

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

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

In [15]:
# Show plot
show(t)


Exercise: Add a crosshair and hover tool to the plot


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

In [17]:
# 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 [18]:
# Add the tools to your figure
t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

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

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

In [21]:
# 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")


Out[21]:
<bokeh.plotting.Figure at 0x109136a10>

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

In [23]:
# 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.orientation = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None

In [24]:
# Show plot
show(t)


[OPTIONAL] Exercise: Style the hover tooltip


In [25]:
# 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.orientation = "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)