svgmain-effects
Main effects
How does the mean response change across each factor's levels?
How to read it
- Read each panel as one factor: mean response at each level.
- Steeper lines mean larger main effects.
- Compare with the dashed grand mean.
- Callout 1: A steep line: a large effect.
- Callout 2: A shallow line: a small effect.
- Callout 3: The grand mean.
Watch out
- If factors interact, a main effect alone can mislead: check the interaction plot too.
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.
- Levels are drawn in the order sent (coded low → high); the y axis is shared across a response's panels so slopes compare. The dashed line is the grand mean of the first factor's level means.
- Main effects can mislead when interactions are large — check the interaction plot and the effects screening first.
# Main effects — Codesplash Chart Lab (recipe "main-effects")
# 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("main-effects-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["factor"] = pd.Categorical(df["factor"].astype("string"), categories=["Temperature", "Pressure", "Concentration", "Stirring"])
df["level"] = pd.Categorical(df["level"].astype("string"), categories=["low", "high"])
_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")
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)))
F = "factor"
L = "level"
M = "mean filtration rate"
RESP = None
factors = levels_of(df[F])
fig, axes = plt.subplots(1, len(factors), figsize=(2.2 * len(factors) + 1, 3.6), sharey=True, squeeze=False)
grand = df[df[F].astype(str) == str(factors[0])][M].mean()
for ax, f in zip(axes[0], factors):
d = df[df[F].astype(str) == str(f)]
ax.plot(d[L].astype(str), d[M], marker="o", color=PALETTE[0], linewidth=1.8)
ax.axhline(grand, color=REF, linestyle="--", linewidth=1)
ax.set_title(str(f), fontsize=10, loc="left")
axes[0, 0].set_ylabel(M)
plt.show()Needs pandas, numpy, matplotlib · reads main-effects-demo.csv · app theme from the optional codesplash helper
# Main effects — Codesplash Chart Lab (recipe "main-effects")
# 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("main-effects-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["factor"] = pd.Categorical(df["factor"].astype("string"), categories=["Temperature", "Pressure", "Concentration", "Stirring"])
df["level"] = pd.Categorical(df["level"].astype("string"), categories=["low", "high"])
_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")
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)))
F = "factor"
L = "level"
M = "mean filtration rate"
RESP = None
from plotly.subplots import make_subplots
factors = levels_of(df[F])
fig = make_subplots(rows=1, cols=len(factors), shared_yaxes=True, subplot_titles=[str(f) for f in factors])
grand = df[df[F].astype(str) == str(factors[0])][M].mean()
for k, f in enumerate(factors, start=1):
d = df[df[F].astype(str) == str(f)]
fig.add_scatter(x=d[L].astype(str), y=d[M], mode="lines+markers", line=dict(color=PALETTE[0]), showlegend=False, row=1, col=k)
fig.add_hline(y=grand, line=dict(color=REF, dash="dash", width=1), row=1, col=k)
fig.update_yaxes(title_text=M, row=1, col=1)
fig.show()Needs pandas, numpy, plotly · reads main-effects-demo.csv · app theme from the optional codesplash helper
# Main effects — Codesplash Chart Lab (recipe "main-effects")
# 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("main-effects-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["factor"]] <- factor(df[["factor"]], levels = c("Temperature", "Pressure", "Concentration", "Stirring"))
df[["level"]] <- factor(df[["level"]], levels = c("low", "high"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
f_col <- "factor"
l_col <- "level"
m_col <- "mean filtration rate"
resp_col <- NULL
d <- data.frame(f = factor(as.character(df[[f_col]]), levels = levels_of(df[[f_col]])), l = as.character(df[[l_col]]), m = df[[m_col]])
d$l <- factor(d$l, levels = unique(d$l))
grand <- mean(d$m[d$f == levels(d$f)[1]])
p <- ggplot(d, aes(l, m, group = f)) + geom_hline(yintercept = grand, colour = ref_col, linetype = "dashed") +
geom_line(colour = cs_cat[1]) + geom_point(colour = cs_cat[1], size = 2.2) +
facet_wrap(~f, nrow = 1, scales = "free_x") + labs(x = NULL, y = m_col) + theme_cs
print(p)Needs ggplot2 · reads main-effects-demo.csv · app theme from the optional codesplashr helper