svgmc-distribution
Monte Carlo distribution
Across all simulated scenarios, how likely is each outcome — and of missing the target?
How to read it
- Read the histogram as the spread of simulated outcomes.
- Read the curve for the cumulative chance, on the right axis.
- Read the shaded part as the chance of missing the target.
- Callout 1: The chance of missing the target.
- Callout 2: P5, P50 and P95.
- Callout 3: The cumulative chance.
Watch out
- The result is only as good as your input distributions. Simulated precision isn't real-world precision.
Defaults
- Target (null = none)
- 0
- The outcome you want to reach; the chart shows the chance of missing it.
- Range -1,000,000,000,000 to 1,000,000,000,000, step 1
- Percentiles
- P5 · P50 · P95
- Which percentiles to mark.
- Also: P10 · P50 · P90 · P1 · P50 · P99 · P25 · P50 · P75
Pinned in the code
- Raw draws are binned on equal-width edges (Sturges × 2, 30–80 bins); percentiles are type 7 (R default) on the draws. Pre-binned input is drawn as sent, with percentiles interpolated within bins.
- P(value < target) counts draws strictly below the target. Draws come from the shared random stream, so Python and R simulations agree draw for draw.
# Monte Carlo distribution — Codesplash Chart Lab (recipe "mc-distribution")
# controls: target=0, percentiles=5-50-95
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("mc-distribution-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
V = "profit ($k)"
BL = None
BH = None
N = None
TARGET, PCTS = 0, [5, 50, 95]
fig, ax = plt.subplots(figsize=(8, 4.5))
if V:
v = df[V].dropna().to_numpy()
k = max(30, min(80, 2 * int(np.ceil(np.log2(len(v)) + 1))))
w = np.full(len(v), 1 / len(v))
counts, edges, _ = ax.hist(v, bins=k, weights=w, color=PALETTE[0], alpha=0.55)
pv = np.percentile(v, PCTS) # numpy's "linear" = type 7
else:
b = df.dropna(subset=[BL, BH, N]).sort_values(BL)
share = b[N] / b[N].sum()
ax.bar(b[BL], share, width=b[BH] - b[BL], align="edge", color=PALETTE[0], alpha=0.55)
edges, counts = np.r_[b[BL].to_numpy(), b[BH].iloc[-1]], share.to_numpy()
cum = np.r_[0, np.cumsum(counts)]
pv = np.interp(np.array(PCTS) / 100, cum, edges)
ax2 = ax.twinx()
ax2.plot(edges, np.r_[0, np.cumsum(counts)], color="black", linewidth=1.4)
ax2.set_ylim(0, 1.02)
ax2.set_ylabel("cumulative probability")
for p, x in zip(PCTS, pv):
ax.axvline(x, color=PALETTE[2], linestyle="--", linewidth=1)
ax.annotate(f"P{p}", (x, 1), xycoords=("data", "axes fraction"), ha="left", va="top", fontsize=8, color=PALETTE[2])
if TARGET is not None:
ax.axvline(TARGET, color="#ce5342", linewidth=1.6)
ax.set_xlabel(V or "value")
ax.set_ylabel("share of draws")
plt.show()Needs pandas, numpy, matplotlib · reads mc-distribution-demo.csv · app theme from the optional codesplash helper
# Monte Carlo distribution — Codesplash Chart Lab (recipe "mc-distribution")
# controls: target=0, percentiles=5-50-95
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("mc-distribution-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
V = "profit ($k)"
BL = None
BH = None
N = None
TARGET, PCTS = 0, [5, 50, 95]
fig = go.Figure()
if V:
v = df[V].dropna()
fig.add_histogram(x=v, histnorm="probability", nbinsx=max(30, min(80, 2 * int(np.ceil(np.log2(len(v)) + 1)))), marker_color=PALETTE[0], opacity=0.6, name=V)
pv = np.percentile(v, PCTS)
else:
b = df.dropna(subset=[BL, BH, N]).sort_values(BL)
fig.add_bar(x=(b[BL] + b[BH]) / 2, y=b[N] / b[N].sum(), width=b[BH] - b[BL], marker_color=PALETTE[0], opacity=0.6, name="share")
cum = np.r_[0, np.cumsum(b[N] / b[N].sum())]
pv = np.interp(np.array(PCTS) / 100, cum, np.r_[b[BL].to_numpy(), b[BH].iloc[-1]])
for p, x in zip(PCTS, pv):
fig.add_vline(x=x, line=dict(color=PALETTE[2], dash="dash", width=1), annotation_text=f"P{p}")
if TARGET is not None:
fig.add_vline(x=TARGET, line=dict(color="#ce5342", width=2), annotation_text="target")
fig.update_layout(xaxis_title=V or "value", yaxis_title="share of draws", bargap=0)
fig.show()Needs pandas, numpy, plotly · reads mc-distribution-demo.csv · app theme from the optional codesplash helper
# Monte Carlo distribution — Codesplash Chart Lab (recipe "mc-distribution")
# controls: target=0, percentiles=5-50-95
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("mc-distribution-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
v_col <- "profit ($k)"
bl_col <- NULL
bh_col <- NULL
n_col <- NULL
target <- 0; pcts <- c(5, 50, 95)
if (!is.null(v_col)) {
v <- df[[v_col]][!is.na(df[[v_col]])]
k <- max(30, min(80, 2 * ceiling(log2(length(v)) + 1)))
pv <- stats::quantile(v, pcts / 100, type = 7, names = FALSE)
p <- ggplot(data.frame(v = v), aes(v)) + geom_histogram(aes(y = after_stat(count / sum(count))), bins = k, fill = cs_cat[1], alpha = 0.55)
} else {
b <- data.frame(lo = df[[bl_col]], hi = df[[bh_col]], n = df[[n_col]]); b <- b[order(b$lo), ]
b$share <- b$n / sum(b$n)
pv <- stats::approx(c(0, cumsum(b$share)), c(b$lo, utils::tail(b$hi, 1)), xout = pcts / 100)$y
p <- ggplot(b) + geom_rect(aes(xmin = lo, xmax = hi, ymin = 0, ymax = share), fill = cs_cat[1], alpha = 0.55)
}
p <- p + geom_vline(xintercept = pv, colour = cs_cat[3], linetype = "dashed") +
annotate("text", x = pv, y = Inf, label = paste0("P", pcts), vjust = 1.5, hjust = -0.1, size = 3, colour = cs_cat[3]) +
{ if (!is.null(target)) geom_vline(xintercept = target, colour = "#ce5342", linewidth = 0.8) } +
labs(x = if (is.null(v_col)) "value" else v_col, y = "share of draws") + theme_cs
print(p)Needs ggplot2 · reads mc-distribution-demo.csv · app theme from the optional codesplashr helper