Exercise: Reproduce the timeseries chart using the plotting interface
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()
In [5]:
# Create your plot
p = figure()
p.line(df['datetime'], df['anomaly'])
p.line(df['datetime'], df['moving_average'])
Out[5]:
In [6]:
# Show plot
show(p)
Out[6]:
Exercise: Style the plot appropriately
Ideas:
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]:
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.location = "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)
Out[15]:
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]:
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.location = "bottom_right"
t.grid.grid_line_alpha=0.2
t.toolbar_location=None
In [24]:
# Show plot
show(t)
Out[24]:
[OPTIONAL] Exercise: Style the hover tooltip
In [26]:
# New figure
t = figure(x_axis_type = "datetime", width=800, height=400,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)
Out[26]:
In [ ]: