svgcensored-fit
Censored regression (Tobit) fit
How does a Tobit model's latent mean relate to outcomes that pile up at a limit?
How to read it
- Read each point as an outcome against its fitted latent mean.
- Squares mark rows censored at the limit.
- The latent mean extends below the limit, which is why simple regression would be biased.
- Callout 1: Censored rows, piled up at the limit.
- Callout 2: Uncensored rows follow the line.
- Callout 3: The line y = x.
Watch out
- If far more than half the rows are censored, the estimates lean heavily on normality.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
- Status values containing “left/lower” or “right/upper” mark censored rows; everything else is uncensored.
- Censored points sit on the limit line by construction — their true latent value is beyond it, which is what the Tobit likelihood accounts for.
# Censored regression (Tobit) fit — Codesplash Chart Lab (recipe "censored-fit")
# 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("censored-fit-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["status"] = pd.Categorical(df["status"].astype("string"), categories=["observed", "left-censored"])
_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")
F = "x′β"
O = "hours"
ST = "status"
d = df.dropna(subset=[F, O])
status = d[ST].astype(str).str.lower() if ST else pd.Series("", index=d.index)
cens = status.str.contains("left|lower|below|right|upper|above")
lim = [min(d[F].min(), d[O].min()), max(d[F].max(), d[O].max())]
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(lim, lim, color=REF, linestyle="--", label="y = x")
ax.scatter(d.loc[~cens, F], d.loc[~cens, O], s=14, color=PALETTE[0], alpha=0.6, label="uncensored")
ax.scatter(d.loc[cens, F], d.loc[cens, O], s=26, marker="s", facecolors="none", edgecolors="#c27c0e", label="censored (at the limit)")
ax.set_xlabel("fitted latent mean (x'b)")
ax.set_ylabel(O)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads censored-fit-demo.csv · app theme from the optional codesplash helper
# Censored regression (Tobit) fit — Codesplash Chart Lab (recipe "censored-fit")
# 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("censored-fit-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["status"] = pd.Categorical(df["status"].astype("string"), categories=["observed", "left-censored"])
_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")
F = "x′β"
O = "hours"
ST = "status"
d = df.dropna(subset=[F, O])
status = d[ST].astype(str).str.lower() if ST else pd.Series("", index=d.index)
cens = status.str.contains("left|lower|below|right|upper|above")
lim = [min(d[F].min(), d[O].min()), max(d[F].max(), d[O].max())]
fig = go.Figure()
fig.add_scatter(x=lim, y=lim, mode="lines", line=dict(color=REF, dash="dash"), name="y = x")
fig.add_scatter(x=d.loc[~cens, F], y=d.loc[~cens, O], mode="markers", marker=dict(color=PALETTE[0], size=6, opacity=0.6), name="uncensored")
fig.add_scatter(x=d.loc[cens, F], y=d.loc[cens, O], mode="markers", marker=dict(symbol="square-open", color="#c27c0e", size=8), name="censored")
fig.update_layout(xaxis_title="fitted latent mean (x'b)", yaxis_title=O)
fig.show()Needs pandas, numpy, plotly · reads censored-fit-demo.csv · app theme from the optional codesplash helper
# Censored regression (Tobit) fit — Codesplash Chart Lab (recipe "censored-fit")
# 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("censored-fit-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["status"]] <- factor(df[["status"]], levels = c("observed", "left-censored"))
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
f_col <- "x′β"
o_col <- "hours"
st_col <- "status"
d <- df[!is.na(df[[f_col]]) & !is.na(df[[o_col]]), ]
st <- if (is.null(st_col)) rep("", nrow(d)) else tolower(as.character(d[[st_col]]))
d <- data.frame(fit = d[[f_col]], obs = d[[o_col]], censored = grepl("left|lower|below|right|upper|above", st))
p <- ggplot(d, aes(fit, obs)) + geom_abline(intercept = 0, slope = 1, linetype = "dashed", colour = ref_col) +
geom_point(aes(shape = censored, colour = censored), size = 1.8) +
scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 0), labels = c("uncensored", "censored"), name = NULL) +
scale_colour_manual(values = c("FALSE" = cs_cat[1], "TRUE" = "#c27c0e"), labels = c("uncensored", "censored"), name = NULL) +
labs(x = "fitted latent mean (x'b)", y = o_col) + theme_cs
print(p)Needs ggplot2 · reads censored-fit-demo.csv · app theme from the optional codesplashr helper