svgarm-share
Arm shares
How quickly does each policy shift its plays toward the best arm?
12
How to read it
- Read each panel as one policy's share of plays per arm over rounds.
- A policy that shifts quickly to one arm is exploiting early.
- Compare how soon the best arm's band takes over.
- 1Callout 1: The best arm's share grows.
- 2Callout 2: Early: exploring all arms.
Watch out
- Very fast convergence can lock on to a wrong arm if rewards change.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Shares are renormalized to sum to 1 at each round; long series are thinned to about 400 rounds per panel.
# Arm shares — Codesplash Chart Lab (recipe "arm-share")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("arm-share-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (4.0%)", "B (4.6%)", "C (5.1%)", "D (6.0%)"])
df["policy"] = pd.Categorical(df["policy"].astype("string"), categories=["UCB1", "Thompson sampling"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
T = "round"
S = "share of plays"
ARM = "arm"
POL = "policy"
policies = levels_of(df[POL]) if POL else [None]
arms = levels_of(df[ARM])
fig, axes = plt.subplots(1, len(policies), figsize=(4 * len(policies) + 1, 3.8), sharey=True, squeeze=False)
for ax, pol in zip(axes[0], policies):
d = df if pol is None else df[df[POL].astype(str) == str(pol)]
wide = d.pivot_table(index=T, columns=ARM, values=S, aggfunc="sum", observed=False).reindex(columns=arms).fillna(0)
wide = wide.div(wide.sum(axis=1).replace(0, 1), axis=0) # shares sum to 1
ax.stackplot(wide.index, wide.T.values, colors=PALETTE[: len(arms)], labels=[str(a) for a in arms], alpha=0.85,
hatch=[SERIES_HATCHES[i % 8] for i in range(len(arms))], hatchcolor=HATCH_INK, linewidth=0) # texture per arm, as in the app
ax.set_title(str(pol) if pol is not None else "", fontsize=10, loc="left")
ax.set_xlabel(T)
axes[0, 0].set_ylabel("share of plays")
axes[0, 0].legend(fontsize=8, loc="lower left")
plt.show()Needs pandas, numpy, matplotlib · reads arm-share-demo.csv · app theme from the optional codesplash helper
# Arm shares — Codesplash Chart Lab (recipe "arm-share")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("arm-share-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (4.0%)", "B (4.6%)", "C (5.1%)", "D (6.0%)"])
df["policy"] = pd.Categorical(df["policy"].astype("string"), categories=["UCB1", "Thompson sampling"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
T = "round"
S = "share of plays"
ARM = "arm"
POL = "policy"
d = df.dropna(subset=[T, S, ARM]).sort_values(T)
fig = px.area(d, x=T, y=S, color=ARM, facet_col=POL, color_discrete_sequence=PALETTE, groupnorm="fraction",
pattern_shape=ARM, pattern_shape_sequence=SERIES_HATCHES, # texture per arm, as in the app
category_orders={ARM: levels_of(d[ARM])} | ({POL: levels_of(d[POL])} if POL else {}))
fig.update_traces(fillpattern_fgcolor=HATCH_INK, fillpattern_fillmode="overlay")
fig.update_layout(yaxis_title="share of plays", legend_title=None)
fig.show()Needs pandas, numpy, plotly · reads arm-share-demo.csv · app theme from the optional codesplash helper
# Arm shares — Codesplash Chart Lab (recipe "arm-share")
# controls: defaults
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("arm-share-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("A (4.0%)", "B (4.6%)", "C (5.1%)", "D (6.0%)"))
df[["policy"]] <- factor(df[["policy"]], levels = c("UCB1", "Thompson sampling"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "round"
s_col <- "share of plays"
arm_col <- "arm"
pol_col <- "policy"
d <- data.frame(t = df[[t_col]], s = df[[s_col]], arm = factor(as.character(df[[arm_col]]), levels = levels_of(df[[arm_col]])),
pol = if (is.null(pol_col)) "" else factor(as.character(df[[pol_col]]), levels = levels_of(df[[pol_col]])))
p <- ggplot(d, aes(t, s, fill = arm)) + geom_area(position = "fill", alpha = 0.85) + facet_wrap(~pol) +
scale_fill_manual(values = cs_textures(cs_cat)) + scale_y_continuous(labels = function(v) paste0(round(v * 100), "%")) + # texture per arm, as in the app
labs(x = t_col, y = "share of plays", fill = NULL) + theme_cs
print(p)Needs ggplot2 · reads arm-share-demo.csv · app theme from the optional codesplashr helper