Skip to content

Instantly share code, notes, and snippets.

@afonsobspinto
Created October 22, 2020 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afonsobspinto/5f4e70a4407113c3dd5fe30d05cf2458 to your computer and use it in GitHub Desktop.
Save afonsobspinto/5f4e70a4407113c3dd5fe30d05cf2458 to your computer and use it in GitHub Desktop.
unemployment heatmap
from math import pi
import pandas as pd
from bokeh.io import show
from bokeh.models import BasicTicker, ColorBar, LinearColorMapper, PrintfTickFormatter
from bokeh.plotting import figure
from bokeh.sampledata.unemployment1948 import data
import numpy as np
from bokeh.models.tickers import FixedTicker
import colorcet as cc
data['Year'] = data['Year'].astype(str)
data = data.set_index('Year')
data.drop('Annual', axis=1, inplace=True)
data.columns.name = 'Month'
years = list(data.index)
months = list(data.columns)
# reshape to 1D array or rates with a month and year for each row.
df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()
mapper = LinearColorMapper(palette=cc.palette['diverging_tritanopic_cwr_75_98_c20'], low=3, high=df.rate.max())
mapper_world = LinearColorMapper(palette=cc.palette['linear_blue_95_50_c20'], low=0, high=16)
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
p = figure(title="US Unemployment ({0} - {1})".format(years[0], years[-1]),
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
tools=TOOLS, toolbar_location='below',
tooltips=[('date', '@Month @Year'), ('rate', '@rate')])
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "7px"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = pi / 3
p.rect(x="Year", y="Month", width=1, height=1,
source=df,
fill_color={'field': 'rate', 'transform': mapper},
line_color=None)
n_ticks = 5
ticks = np.linspace(df.rate.min(), df.rate.max(), n_ticks).round(1)
color_ticks = FixedTicker(ticks=ticks)
color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="7px",
ticker=color_ticks,
label_standoff=6, border_line_color=None, location=(0, 0))
ticks_world = np.linspace(0, 16, n_ticks).round(1)
color_ticks_world = FixedTicker(ticks=ticks_world)
color_bar_world = ColorBar(color_mapper=mapper_world, major_label_text_font_size="7px",
ticker=color_ticks_world,
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
p.add_layout(color_bar_world, 'right')
show(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment