svgcalendar-heatmap
Calendar heatmap
Which days are busy or quiet across a whole year — weekly rhythms, holidays, gaps?
How to read it
- Read a row as a weekday and a column as a week.
- Look for columns or rows that stand out: holidays and weekly rhythms.
- Blank cells mean no data, which is different from zero.
- Callout 1: Rows are weekdays.
- Callout 2: A block of darker days.
- Callout 3: Colour scale: the daily value.
Watch out
- An extreme day can wash out the rest of a linear colour scale.
Defaults
- Daily value
- Sum
- How rows combine into one number per day.
- Also: Mean · Row count
- Colour scale
- Linear (0 → max)
- Linear shows the dense cells; log or square root reveals the sparse ones too.
- Also: Quantile (rank)
- Years shown (latest)
- 3
- How many of the latest years to show.
- Range 1 to 5, step 1
Pinned in the code
- Rows are aggregated per UTC calendar day (sum, mean or count).
- Columns are weeks counted from the Monday on or before 1 January; rows are ISO weekdays (Monday first).
- Linear colour maps 0 → the maximum day; quantile colour maps each day's rank among days with data (robust to outliers).
- Days inside the data range without rows are drawn as empty cells; days outside it are omitted.
- All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")
# controls: agg=sum, scale=linear, years=3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("calendar-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def daily_values(d, time, value, agg):
"""Daily sum / mean / row count per UTC calendar day."""
day = d[time].dt.floor("D")
if value is None or agg == "count":
return d.groupby(day).size().astype(float)
return d.groupby(day)[value].agg(agg)
def calendar_grid(daily, year):
"""7 × 54 grid: columns are weeks from the Monday on or before 1 January, rows ISO weekdays."""
jan1 = pd.Timestamp(year=year, month=1, day=1)
origin = jan1 - pd.Timedelta(days=jan1.day_of_week)
grid = np.full((7, 54), np.nan)
inside = np.zeros((7, 54), bool)
for day in pd.date_range(max(daily.index.min(), jan1), min(daily.index.max(), pd.Timestamp(year=year, month=12, day=31)), freq="D"):
w, dow = (day - origin).days // 7, day.day_of_week
inside[dow, w] = True # days inside the data range without rows stay empty
if day in daily.index:
grid[dow, w] = daily[day]
return grid, inside
AGG, SCALE, YEARS = "sum", "linear", 3
d = df.dropna(subset=["date", "commits"])
daily = daily_values(d, "date", "commits", AGG)
if SCALE == "quantile": # each day's rank among days with data (robust to outliers)
daily = daily.rank(pct=True)
years = sorted(daily.index.year.unique())[-YEARS:]
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
vmax = 1 if SCALE == "quantile" else daily.max() # linear: 0 → the maximum day
fig, axes = plt.subplots(len(years), 1, figsize=(11, 1.7 * len(years)), squeeze=False)
for ax, year in zip(axes[:, 0], years):
grid, inside = calendar_grid(daily, year)
ax.imshow(np.where(inside, 0.0, np.nan), cmap=LinearSegmentedColormap.from_list("e", [GREY, GREY]), aspect="equal", alpha=0.35)
im = ax.imshow(grid, cmap=cmap, vmin=0, vmax=vmax, aspect="equal")
ax.set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], fontsize=7)
jan1 = pd.Timestamp(year=year, month=1, day=1)
origin = jan1 - pd.Timedelta(days=jan1.day_of_week)
starts = [pd.Timestamp(year=year, month=m, day=1) for m in range(1, 13)]
ax.set_xticks([(s - origin).days // 7 for s in starts], [s.strftime("%b") for s in starts], fontsize=7)
ax.set_title(str(year), fontsize=9, loc="left")
ax.grid(False)
fig.colorbar(im, ax=axes[:, 0].tolist(), shrink=0.6, label=AGG + " of " + "commits" if AGG != "count" else "rows")
plt.show()Needs pandas, numpy, matplotlib · reads calendar-heatmap-demo.csv · app theme from the optional codesplash helper
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")
# controls: agg=sum, scale=linear, years=3
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("calendar-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def daily_values(d, time, value, agg):
"""Daily sum / mean / row count per UTC calendar day."""
day = d[time].dt.floor("D")
if value is None or agg == "count":
return d.groupby(day).size().astype(float)
return d.groupby(day)[value].agg(agg)
def calendar_grid(daily, year):
"""7 × 54 grid: columns are weeks from the Monday on or before 1 January, rows ISO weekdays."""
jan1 = pd.Timestamp(year=year, month=1, day=1)
origin = jan1 - pd.Timedelta(days=jan1.day_of_week)
grid = np.full((7, 54), np.nan)
inside = np.zeros((7, 54), bool)
for day in pd.date_range(max(daily.index.min(), jan1), min(daily.index.max(), pd.Timestamp(year=year, month=12, day=31)), freq="D"):
w, dow = (day - origin).days // 7, day.day_of_week
inside[dow, w] = True # days inside the data range without rows stay empty
if day in daily.index:
grid[dow, w] = daily[day]
return grid, inside
AGG, SCALE, YEARS = "sum", "linear", 3
d = df.dropna(subset=["date", "commits"])
daily = daily_values(d, "date", "commits", AGG)
if SCALE == "quantile":
daily = daily.rank(pct=True)
years = sorted(daily.index.year.unique())[-YEARS:]
fig = make_subplots(rows=len(years), cols=1, subplot_titles=[str(y) for y in years], vertical_spacing=0.08)
for i, year in enumerate(years):
grid, _ = calendar_grid(daily, year)
fig.add_heatmap(z=grid, y=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], zmin=0,
zmax=1 if SCALE == "quantile" else daily.max(), showscale=i == 0, xgap=1, ygap=1, row=i + 1, col=1)
fig.update_yaxes(autorange="reversed", row=i + 1, col=1)
fig.update_layout(height=170 * len(years))
fig.show()Needs pandas, numpy, plotly · reads calendar-heatmap-demo.csv · app theme from the optional codesplash helper
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")
# controls: agg=sum, scale=linear, years=3
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("calendar-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
agg <- "sum"; scale <- "linear"; years_shown <- 3
t <- as.POSIXct(df[["date"]], tz = "UTC")
ok <- !is.na(t) & !is.na(df[["commits"]])
day <- as.Date(format(t[ok], "%Y-%m-%d", tz = "UTC")) # UTC calendar day
daily <- if (agg == "count") tapply(day, day, length) else tapply(df[["commits"]][ok], day, if (agg == "mean") mean else sum)
daily <- stats::setNames(as.numeric(daily), names(daily))
if (scale == "quantile") daily <- rank(daily) / length(daily) # rank among days with data
all_days <- seq(min(as.Date(names(daily))), max(as.Date(names(daily))), by = "day") # empty days inside the range
cal <- data.frame(day = all_days, value = unname(daily[format(all_days)]))
cal$year <- as.integer(format(cal$day, "%Y"))
cal <- cal[cal$year %in% utils::tail(sort(unique(cal$year)), years_shown), ]
jan1 <- as.Date(sprintf("%d-01-01", cal$year))
origin <- jan1 - (as.POSIXlt(jan1)$wday + 6) %% 7 # Monday on or before 1 January
cal$week <- as.integer(cal$day - origin) %/% 7
cal$dow <- factor((as.POSIXlt(cal$day)$wday + 6) %% 7, levels = 0:6, labels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
p <- ggplot(cal, aes(week, dow, fill = value)) +
geom_tile(colour = "white", linewidth = 0.3) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], na.value = grey_col, limits = c(0, if (scale == "quantile") 1 else max(daily)), name = if (agg == "count") "rows" else paste(agg, "commits")) +
scale_y_discrete(limits = rev) +
facet_wrap(~year, ncol = 1) +
coord_equal() + labs(x = "week of year", y = NULL) +
theme_cs + theme(panel.grid = element_blank())
print(p)Needs ggplot2 · reads calendar-heatmap-demo.csv · app theme from the optional codesplashr helper
-- Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")
-- controls: agg=sum, scale=linear, years=3
-- one cell per UTC day: weeks counted from the Monday on or before 1 January, ISO weekday rows
WITH d AS (
SELECT "date"::DATE AS day, sum("commits") AS value, count(*) AS n
FROM read_csv('calendar-heatmap-demo.csv')
WHERE "date" IS NOT NULL AND "commits" IS NOT NULL
GROUP BY ALL
)
SELECT day, year(day) AS year, isodow(day) - 1 AS dow,
datediff('day', make_date(year(day), 1, 1) - to_days(CAST(isodow(make_date(year(day), 1, 1)) - 1 AS INTEGER)), day) // 7 AS week,
value, n
FROM d
ORDER BY day;Needs duckdb · reads calendar-heatmap-demo.csv