svgdensity-compare
Real vs synthetic distribution
Does the synthetic data reproduce the shape of a numeric column?
How to read it
- Read the fill as the real data, the line as the synthetic.
- They should overlap closely.
- Look at the humps and tails: synthetic methods often smooth these away.
- Callout 1: Synthetic is lower at this peak.
- Callout 2: A good match on the second hump.
Watch out
- Matching each column alone doesn't mean relationships between columns are kept.
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 or the host's scorecard); the chart computes nothing statistical.
- Both densities are evaluated on the same grid with the same bandwidth (the scorecard pins it), so differences are in the data, not the smoothing. The KS complement for the column is in the scorecard table.
# Real vs synthetic distribution — Codesplash Chart Lab (recipe "density-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("density-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 (copula)"])
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)))
X = "age"
D = "density"
S = "source"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
d = df if name is None else df[df[S].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
if i == 0:
ax.fill_between(d[X], d[D], color=PALETTE[0], alpha=0.2, lw=0)
ax.plot(d[X], d[D], color=PALETTE[i % len(PALETTE)], linewidth=1.6 if i == 0 else 2, label=name)
ax.set_xlabel(X)
ax.set_ylabel("density")
ax.set_ylim(bottom=0)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads density-compare-demo.csv · app theme from the optional codesplash helper
# Real vs synthetic distribution — Codesplash Chart Lab (recipe "density-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("density-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 (copula)"])
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)))
X = "age"
D = "density"
S = "source"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
d = df if name is None else df[df[S].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig = go.Figure()
for i, (name, d) in enumerate(series):
fig.add_scatter(x=d[X], y=d[D], mode="lines", fill="tozeroy" if i == 0 else None, name=name, line=dict(color=PALETTE[i % len(PALETTE)], width=2))
fig.update_layout(xaxis_title=X, yaxis_title="density")
fig.show()Needs pandas, numpy, plotly · reads density-compare-demo.csv · app theme from the optional codesplash helper
# Real vs synthetic distribution — Codesplash Chart Lab (recipe "density-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("density-compare-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["source"]] <- factor(df[["source"]], levels = c("real", "synthetic (copula)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "age"
d_col <- "density"
s_col <- "source"
d <- data.frame(x = df[[x_col]], dens = df[[d_col]], s = factor(as.character(df[[s_col]]), levels = levels_of(df[[s_col]])))
p <- ggplot(d, aes(x, dens, colour = s)) + geom_area(data = d[d$s == levels(d$s)[1], ], aes(fill = s), alpha = 0.2, colour = NA) +
geom_line(linewidth = 0.9) + scale_colour_manual(values = cs_cat) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = x_col, y = "density", colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads density-compare-demo.csv · app theme from the optional codesplashr helper