# Real vs synthetic category shares — Codesplash Chart Lab (recipe "share-compare")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("share-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["source"] = pd.Categorical(df["source"].astype("string"), categories=["real", "synthetic (CART)"])
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)))
L = "employment"
SH = "share"
S = "source"
sources = levels_of(df[S])
wide = df.pivot_table(index=L, columns=S, values=SH, aggfunc="sum", observed=False).reindex(columns=sources).fillna(0)
wide = wide.sort_values(sources[0]).tail(20) # largest real share on top
h = 0.8 / len(sources)
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(wide))
for j, s in enumerate(sources):
ax.barh(y + (len(sources) - 1 - j) * h - 0.4 + h / 2, wide[s], height=h * 0.95, color=PALETTE[j % len(PALETTE)], label=str(s))
ax.set_yticks(y, wide.index.astype(str))
if len(sources) >= 2:
ax.set_title(f"total variation distance {0.5 * (wide[sources[0]] - wide[sources[1]]).abs().sum():.3f}", fontsize=9, loc="left")
ax.set_xlabel(SH)
ax.legend(fontsize=8)
plt.show()
Needs pandas, numpy, matplotlib · reads share-compare-demo.csv · app theme from the optional codesplash helper
# Real vs synthetic category shares — Codesplash Chart Lab (recipe "share-compare")
# 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
df = pd.read_csv("share-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["source"] = pd.Categorical(df["source"].astype("string"), categories=["real", "synthetic (CART)"])
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)))
L = "employment"
SH = "share"
S = "source"
fig = px.bar(df, x=SH, y=L, color=S, orientation="h", barmode="group", color_discrete_sequence=PALETTE, category_orders={S: levels_of(df[S])})
fig.update_layout(legend_title=None, yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads share-compare-demo.csv · app theme from the optional codesplash helper
# Real vs synthetic category shares — Codesplash Chart Lab (recipe "share-compare")
# 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))
df <- read.csv("share-compare-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["employment"]] <- factor(df[["employment"]])
df[["source"]] <- factor(df[["source"]], levels = c("real", "synthetic (CART)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
l_col <- "employment"
sh_col <- "share"
s_col <- "source"
d <- data.frame(l = as.character(df[[l_col]]), sh = df[[sh_col]], s = factor(as.character(df[[s_col]]), levels = levels_of(df[[s_col]])))
first <- d[d$s == levels(d$s)[1], ]
d$l <- factor(d$l, levels = unique(first$l[order(first$sh)]))
p <- ggplot(d, aes(sh, l, fill = s)) + geom_col(position = position_dodge2(reverse = TRUE)) + scale_fill_manual(values = cs_cat) +
labs(x = sh_col, y = NULL, fill = NULL) + theme_cs
print(p)
Needs ggplot2 · reads share-compare-demo.csv · app theme from the optional codesplashr helper