Graphique d'interaction
Moyennes de groupes avec intervalles de confiance à 95 % pour deux facteurs, avec ANOVA à deux facteurs.

Un graphique d'interaction montre la moyenne de la variable réponse pour chaque combinaison de deux facteurs : un facteur sur l'axe des x, l'autre sous forme de lignes colorées légèrement décalées. Chaque moyenne est accompagnée de son intervalle de confiance à 95 %. Des lignes parallèles indiquent que les deux facteurs agissent indépendamment ; des lignes qui convergent, divergent ou se croisent signalent une interaction.
Le contexte est celui de de Marcellis-Warin, Marty, Thelisson et Warin (2022, AI and Ethics), sur l'intelligence artificielle et la manipulation des consommateurs. Les chiffres sont ici simulés à des fins d'illustration — un score de vulnérabilité à la manipulation de 1 à 7 pour n = 480 consommateurs, selon la tranche d'âge et selon une littératie numérique faible ou élevée (60 par cellule) — et ne sont ni les données ni les résultats de l'article. L'ANOVA à deux facteurs (sommes des carrés de type II) provient de statsmodels.formula.api.ols et de statsmodels.stats.anova.anova_lm, avec η² partiel pour chaque terme ; les intervalles utilisent la loi de Student.
Le code et le texte à l'intérieur des figures sont en anglais.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats
from statsmodels.stats.anova import anova_lm
# Simulated data, set in the context of de Marcellis-Warin et al. (2022) [dmw2022manip]
# Data: susceptibility score (1–7) by age group and digital literacy, 60 consumers per cell
rng = np.random.default_rng(2022)
classes = ["18–29", "30–44", "45–59", "60+"]
df = pd.DataFrame([(a, lit) for a in range(4) for lit in ["High", "Low"] for _ in range(60)],
columns=["age", "literacy"])
low = (df.literacy == "Low").to_numpy()
df["score"] = np.clip(3.4 + 0.15 * df.age + low * (0.3 + 0.35 * df.age)
+ rng.normal(0, 1.0, len(df)), 1, 7)
df["age_group"] = pd.Categorical(np.array(classes)[df.age], classes)
# Two-way ANOVA with interaction (type II) + partial eta squared
aov = anova_lm(smf.ols("score ~ C(age_group) * C(literacy)", data=df).fit(), typ=2)
ss_res = aov.loc["Residual", "sum_sq"]
aov["eta_p"] = aov.sum_sq / (aov.sum_sq + ss_res)
df_res = int(aov.loc["Residual", "df"])
# Means and t-based 95% CIs per cell
cells = df.groupby(["literacy", "age_group"], observed=True).score.agg(["mean", "sem", "count"])
cells["half"] = cells["sem"] * stats.t.ppf(0.975, cells["count"] - 1)
fig, ax = plt.subplots(figsize=(8, 5))
x = np.arange(len(classes))
for (lit, c, dx) in [("High", "#007AFF", -0.06), ("Low", "#FF3B30", 0.06)]:
m = cells.loc[lit].reindex(classes)
ax.errorbar(x + dx, m["mean"], yerr=m["half"], color=c, lw=2, capsize=0,
elinewidth=2, marker="o", ms=9, mec="white", mew=1.8)
ax.annotate(f"{lit} digital\nliteracy", (x[-1] + dx, m["mean"].iloc[-1]), xytext=(14, 0),
textcoords="offset points", va="center", fontsize=10.5,
fontweight="semibold", color=c)
ax.set_xticks(x, classes)
ax.set_xlim(-0.3, len(classes) - 0.3)
ax.set_xlabel("Age group (60 consumers per literacy level in each group)")
ax.set_ylabel("Susceptibility to manipulation\n(1–7 score; mean ± 95% CI)")
# One "F(df1, df2) = …, p …, η²p = …" string per ANOVA term
stat = {}
for term, label in [("C(age_group)", "age"), ("C(literacy)", "literacy"),
("C(age_group):C(literacy)", "age × literacy")]:
r = aov.loc[term]
pval = "< .001" if r["PR(>F)"] < .001 else f"= {r['PR(>F)']:.2f}"
stat[label] = f"{label} F({r.df:.0f}, {df_res}) = {r.F:.1f}, p {pval}, η²p = {r.eta_p:.2f}"
gap = cells.loc["Low", "mean"] - cells.loc["High", "mean"]
ax.set_title(f"The literacy gap in susceptibility widens with age, "
f"from {gap.iloc[0]:.1f} to {gap.iloc[-1]:.1f} points", pad=40)
ax.text(0, 1.075, f"Two-way ANOVA (type II), n = {len(df)} consumers (simulated) · {stat['literacy']}",
transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
ax.text(0, 1.02, f"{stat['age']} · {stat['age × literacy']}", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# Interaction plot: the R equivalent of plot.py
# Simulated data, set in the context of de Marcellis-Warin et al. (2022) [dmw2022manip]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2022)
# Data: susceptibility score (1–7) by age group and digital literacy, 60 consumers per cell
classes <- c("18–29", "30–44", "45–59", "60+")
d <- expand.grid(rep = 1:60, literacy = c("High", "Low"), age = 0:3)
low <- d$literacy == "Low"
d$score <- pmin(pmax(3.4 + 0.15 * d$age + low * (0.3 + 0.35 * d$age) + rnorm(nrow(d), 0, 1.0), 1), 7)
d$age_group <- factor(classes[d$age + 1], levels = classes)
# Two-way ANOVA with interaction + partial eta squared
# (the design is balanced, so these sequential sums of squares equal the type II ones)
aov_table <- anova(lm(score ~ age_group * literacy, data = d))
ss_res <- aov_table["Residuals", "Sum Sq"]
df_res <- aov_table["Residuals", "Df"]
term <- function(row, label) { # one "F(df1, df2) = …, p …, η²p = …" string per term
r <- aov_table[row, ]
pval <- if (r[["Pr(>F)"]] < .001) "< .001" else sprintf("= %.2f", r[["Pr(>F)"]])
sprintf("%s F(%d, %d) = %.1f, p %s, η²p = %.2f", label, r$Df, df_res, r[["F value"]], pval,
r[["Sum Sq"]] / (r[["Sum Sq"]] + ss_res))
}
# Means and t-based 95% CIs per cell
cells <- aggregate(score ~ age_group + literacy, data = d, FUN = function(v)
c(mean = mean(v), half = qt(0.975, length(v) - 1) * sd(v) / sqrt(length(v))))
cells <- cbind(cells[c("age_group", "literacy")], cells$score)
gap <- cells$mean[cells$literacy == "Low"] - cells$mean[cells$literacy == "High"]
dodge <- position_dodge(width = 0.12)
p <- ggplot(cells, aes(age_group, mean, colour = literacy, group = literacy)) +
geom_line(linewidth = 0.9, position = dodge) +
geom_linerange(aes(ymin = mean - half, ymax = mean + half), linewidth = 0.9, position = dodge) +
geom_point(aes(fill = literacy), shape = 21, size = 3.6, colour = "white", stroke = 1,
position = dodge) +
geom_text(data = cells[cells$age_group == "60+", ], aes(label = paste(literacy, "digital\nliteracy")),
hjust = 0, nudge_x = 0.16, fontface = "bold", size = 3.6, lineheight = 0.95) +
scale_colour_manual(values = c(High = "#007AFF", Low = "#FF3B30"), aesthetics = c("colour", "fill"),
guide = "none") +
scale_x_discrete(expand = expansion(add = c(0.3, 0.7))) +
labs(title = sprintf("The literacy gap in susceptibility widens with age, from %.1f to %.1f points",
gap[1], gap[4]),
subtitle = sprintf("Two-way ANOVA (type II), n = %d consumers (simulated) · %s\n%s · %s",
nrow(d), term("literacy", "literacy"), term("age_group", "age"),
term("age_group:literacy", "age × literacy")),
x = "Age group (60 consumers per literacy level in each group)",
y = "Susceptibility to manipulation\n(1–7 score; mean ± 95% CI)") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73", lineheight = 1.15),
panel.grid.minor = element_blank(), panel.grid.major.x = element_blank())
print(p)
Les figures utilisent le style PyStatlas (facultatif) : ajoutez plt.style.use("pystatlas.mplstyle") pour obtenir exactement le même rendu.
Source des données
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - de Marcellis-Warin et al. (2022), AI and consumer manipulation. de Marcellis-Warin, N., Marty, F., Thelisson, E., & Warin, T. (2022). Artificial intelligence and consumer manipulations: From consumer's counter algorithms to firm's self-regulation tools. AI and Ethics, 2(2), 259–268. https://doi.org/10.1007/s43681-022-00149-5
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
Les exemples illustrent des méthodes statistiques. Leurs chiffres sont simulés, sauf mention contraire dans l'entrée, et leurs titres décrivent ce que chaque figure montre dans ces données simulées — ni les résultats des articles cités, ni la position de l'auteur sur la question de fond. Pour les résultats, le contexte et les données, reportez-vous aux articles cités ici.
Comment citer
PyStatlas est créé et maintenu par Thierry Warin. S'il vous a été utile dans vos travaux, merci de le citer.
Warin, T. (2026). Interaction plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/group-comparisons/means-with-ci/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}Plus dans Comparaisons de groupes
Comparaison entre groupes
Violon, boîte et points avec ANOVA de Welch, taille d'effet et tests deux à deux.
ggstatsplot::ggbetweenstats()Comparaison intra-sujets
Mesures répétées avec une ligne par sujet, moyennes, ANOVA à mesures répétées et tests appariés.
ggstatsplot::ggwithinstats()Graphique d'estimation
Données brutes de deux groupes, avec la différence de moyennes et son IC à 95 % par bootstrap.
dabestr::dabest() + plot()