Skip to content

The Bayesian correlation

Test a correlation with a stretched-beta prior, estimate ρ with a credible interval, and keep evidence and strength apart.

Applied ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Describe the stretched-beta prior on ρ and its width
  • Read a Bayes factor and a posterior for ρ together
  • Distinguish strong evidence from a strong correlation

Read first

01

A prior on ρ

Read

The test compares H0:ρ=0H_0: \rho = 0 with an H1H_1 that spreads its belief across correlations from −1 to 1:

H1:ρ∼stretched Beta(1/κ, 1/κ) on (−1,1)H_1: \rho \sim \text{stretched Beta}(1/\kappa,\ 1/\kappa) \text{ on } (-1, 1)

The stretched-beta priorStretched beta priorThe prior on a correlation ρ in the Bayesian correlation test — a Beta(1/κ, 1/κ) stretched to (−1, 1); κ = 1 is uniform. has one setting, its width κ\kappa. At κ=1\kappa = 1 the prior is uniform, so every correlation is equally likely. A smaller κ\kappa pulls belief toward 0.

This is the test Jeffreys proposed, with the width as a choice you state.

02

Predict with few points

Predict

Predict first

Ten points give rr = 0.54. That looks sizeable. With a uniform prior, how strong is the evidence?

Strong for a correlationRoughly neutralStrong for no correlation
Reveal

Roughly neutral: BF10\text{BF}_{10} = 1.21. Ten points can't pin down ρ\rho. The posterior median is 0.44, and its interval runs from −0.17 to 0.80, which includes zero and values near 1.

03

Prior and direction

Reflect

Same ten points, a medium prior (κ\kappa = 0.33), and a positive direction: BF10\text{BF}_{10} = 2.55, against a two-sided 1.43.

The evidence grows because H1H_1 makes sharper predictions. It would be fair only if you'd expected a positive correlation in advance.

The uniform-prior run's robustness range is 1.16 to 1.43. Before you see your own data, what do you expect: any sign, or one?

04

Evidence isn't strength

Predict

Predict first

On 153 days of air-quality data, wind and temperature have a directional BF10\text{BF}_{10} of about 9,827,187.

Does a number that large mean the correlation is strong?

Yes: a huge Bayes factor means a strong correlationNo: it means the data are very clear about ρ ≠ 0Only if the prior was wide
Reveal

No. The sample rr is −0.46, with a posterior median of −0.45. That's moderate. The Bayes factor says that a non-zero ρ\rho predicted the data far better. The posterior says how large it is.

05

Read the card

In the app
Bayesian correlationRecorded · Python and R agreeRecorded 2026-11-17 · 15 values compared · largest relative difference 2.5e-14
R

BF₁₀ = 9827186.99 (κ = 0.577), r = −.46, ρ = -0.45, 90% CrI [-0.55, -0.34]

BF₁₀ (ρ < 0 vs ρ = 0)
9.827e+6
BF₀₁
1.018e-7
Sample r
−0.4580
ρ (posterior median)
−0.4487
90% credible interval
[−0.5481, −0.3367]

Effect size

  • ρ (posterior median) −0.4487 90% CI [−0.5481, −0.3367]

Plots

Prior and posterior of ρHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityρ
Prior9.308e-5−1.0000
Prior0.0474−0.9950
Prior0.0786−0.9900
Prior0.1056−0.9850
Prior0.1301−0.9800
Prior0.1529−0.9750
Prior0.1744−0.9700
Prior0.1949−0.9650
Prior0.2145−0.9600
Prior0.2334−0.9550
Prior0.2516−0.9500
Prior0.2693−0.9450
Prior0.2864−0.9400
Prior0.3031−0.9350
Prior0.3194−0.9300
Prior0.3354−0.9250
Prior0.3509−0.9200
Prior0.3661−0.9150
Prior0.3810−0.9100
Prior0.3957−0.9050
Prior0.4100−0.9000
Prior0.4241−0.8950
Prior0.4380−0.8900
Prior0.4516−0.8850
Prior0.4649−0.8800
Prior0.4781−0.8750
Prior0.4911−0.8700
Prior0.5039−0.8650
Prior0.5164−0.8600
Prior0.5288−0.8550
Prior0.5410−0.8500
Prior0.5531−0.8450
Prior0.5650−0.8400
Prior0.5767−0.8350
Prior0.5883−0.8300
Prior0.5997−0.8250
Prior0.6109−0.8200
Prior0.6221−0.8150
Prior0.6331−0.8100
Prior0.6439−0.8050
Prior0.6546−0.8000
Prior0.6652−0.7950
Prior0.6757−0.7900
Prior0.6860−0.7850
Prior0.6962−0.7800
Prior0.7063−0.7750
Prior0.7163−0.7700
Prior0.7261−0.7650
Prior0.7359−0.7600
Prior0.7455−0.7550
Prior0.7550−0.7500
Prior0.7645−0.7450
Prior0.7738−0.7400
Prior0.7830−0.7350
Prior0.7921−0.7300
Prior0.8011−0.7250
Prior0.8100−0.7200
Prior0.8189−0.7150
Prior0.8276−0.7100
Prior0.8362−0.7050

First 60 of 402 rows.

Bayes factor across prior widthsWould a wider or narrower prior change the conclusion?
View data
BF₁₀prior width κ
1.113e+60.0500
1.410e+60.0549
1.757e+60.0603
2.154e+60.0662
2.600e+60.0727
3.091e+60.0798
3.620e+60.0877
4.179e+60.0963
4.760e+60.1057
5.352e+60.1161
5.945e+60.1275
6.527e+60.1400
7.088e+60.1538
7.619e+60.1689
8.111e+60.1854
8.557e+60.2036
8.952e+60.2236
9.291e+60.2456
9.574e+60.2696
9.797e+60.2961
9.962e+60.3252
9.996e+60.3333
1.007e+70.3571
1.012e+70.3921
1.012e+70.4306
1.007e+70.4729
9.982e+60.5193
9.848e+60.5702
9.827e+60.5774
9.677e+60.6262
9.475e+60.6877
9.244e+60.7551
8.989e+60.8293
8.713e+60.9106
8.421e+61
Bayes factor as rows accumulateHow did the evidence grow as the observations came in?
View data
BF₁₀rows
0.56103
1.1926
1.4728
3.95111
5.54013
9.80216
34.46718
17.45321
2.93023
7.77926
3.46228
4.16631
6.36734
11.82636
15.77239
4.43741
6.70444
5.19646
2.56349
2.82051
4.15254
5.16956
6.08459
6.29961
13.93664
20.17267
66.58369
226.8272
151.7274
52.35077
75.58579
105.6282
109.2884
189.4087
208.4089
385.3592
444.1895
795.0697
2257.16100
3302.92102
2235.86105
2531.60107
2845.76110
3299.41112
4167.05115
4890.34117
7802.21120
42044.54122
210107.60125
1.569e+6128
795728.90130
1.107e+6133
805579.79135
1.033e+6138
1.720e+6140
2.377e+6143
3.372e+6145
1.075e+7148
7.031e+6150
9.827e+6153
Temp against WindHow do two numeric variables move together?
View data
WindTemp
7.40067
872
12.60074
11.50062
14.30056
14.90066
8.60065
13.80059
20.10061
8.60069
6.90074
9.70069
9.20066
10.90068
13.20058
11.50064
1266
18.40057
11.50068
9.70062
9.70059
16.60073
9.70061
1261
16.60057
14.90058
857
1267
14.90081
5.70079
7.40076
8.60078
9.70074
16.10067
9.20084
8.60085
14.30079
9.70082
6.90087
13.80090
11.50087
10.90093
9.20092
882
13.80080
11.50079
14.90077
20.70072
9.20065
11.50073
10.30076
6.30077
1.70076
4.60076
6.30076
875
878
10.30073
11.50080
14.90077

First 60 of 153 rows.

Assumptions

  • Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
  • Linear relationship — Check the scatter plot: ρ measures linear association.
  • Independent observations — Each row should be a separate unit.

Evidence

QuantityValue
BF₁₀ (chosen alternative)9.827e+6
BF₁₀ (two-sided)4.914e+6
P(H₁ | data), equal prior odds1.0000
Posterior mean of ρ−0.4463
  • Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 0.577, restricted to ρ < 0.
  • Evidence: extreme evidence for H₁. With equal prior odds, P(H₁ | data) = 1.000.
  • A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec cbd627e00c0ffd94
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bayes_corr, cs_bayes_prior_scale, cs_bayes_evidence_label (twins of codesplash.stats.bayes)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.parquet", col_select = c("Wind", "Temp")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Wind", "Temp")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Wind", "Temp"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
a <- "Wind"
b <- "Temp"
x <- as.numeric(df[[a]])
y <- as.numeric(df[[b]])
if (length(x) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A Bayesian correlation", min = 3, n = length(x))
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = a)
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = b)
kappa <- cs_bayes_prior_scale("correlation", "wide", 0.333)
alternative <- "less"
cred <- 0.9
res <- cs_bayes_corr(x, y, kappa = kappa, alternative = alternative, cred = cred,
                     robustness = TRUE, sequential = TRUE)
bf10 <- res$bf10
post <- res$post
n <- length(x)

# %% Assumptions
assumptions <- list()
sw <- vapply(list(x, y), function(v) if (length(v) >= 3 && length(v) <= 5000) stats::shapiro.test(v)$p.value else NA_real_, numeric(1))
zs <- function(v) abs((v - mean(v)) / stats::sd(v) * sqrt(length(v) / (length(v) - 1)))
extreme <- sum(zs(x) > 3.5 | zs(y) > 3.5)
if (extreme > 0) {
  status <- "warn"
  detail <- sprintf("%d row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them.", extreme)
} else if (any(!is.na(sw) & sw < 0.05) && n < 30) {
  status <- "warn"
  detail <- "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
} else {
  status <- "pass"
  detail <- "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Bivariate normality", status = status, detail = detail)
assumptions[[length(assumptions) + 1]] <- list(key = "linearity", label = "Linear relationship", status = "info", detail = "Check the scatter plot: ρ measures linear association.")
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info", detail = "Each row should be a separate unit.")

# %% Result
label <- cs_bayes_evidence_label(bf10)
direction <- switch(alternative, "two-sided" = "ρ ≠ 0", greater = "ρ > 0", less = "ρ < 0")
summary <- sprintf(
  "BF₁₀ = %s for a correlation between %s and %s (sample r = %.2f, n = %d): the data are %s times more likely under %s — %s (prior width κ = %s). Under the alternative, ρ is most likely near %.2f (%s credible interval [%.2f, %.2f]).",
  cs_fmt_num(bf10), a, b, res$r, n, cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
  if (bf10 >= 1) sprintf("the alternative (%s)", direction) else "no correlation", label, format(signif(kappa, 3)),
  post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high)
grid <- res$grid
charts <- list(cs_chart("prior_posterior", "prior-posterior", "Prior and posterior of ρ",
  list(x = cs_col("ρ", c(grid, grid)), density = cs_col("density", c(res$prior_density, res$posterior_density)),
       curve = cs_col("curve", c(rep("Prior", length(grid)), rep("Posterior", length(grid))), levels = c("Prior", "Posterior"))),
  controls = list(point = 0, ci_low = post$low, ci_high = post$high, cred = cred, bf10 = bf10)))
if (!is.null(res$robust_r)) {
  charts[[length(charts) + 1]] <- cs_chart("robustness", "bf-robustness", "Bayes factor across prior widths",
    list(x = cs_col("prior width κ", res$robust_r), bf = cs_col("BF₁₀", res$robust_bf)), controls = list(chosen = kappa))
}
if (!is.null(res$seq_n) && length(res$seq_n) >= 2) {
  charts[[length(charts) + 1]] <- cs_chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
    list(n = cs_col("rows", as.numeric(res$seq_n)), bf = cs_col("BF₁₀", res$seq_bf)))
}
rows <- unique(as.integer(round(seq(0, n - 1, length.out = min(n, 5000))))) + 1L
charts[[length(charts) + 1]] <- cs_chart("scatter", "scatter", sprintf("%s against %s", b, a), list(x = cs_col(a, x[rows]), y = cs_col(b, y[rows])))
cs_publish(list(
  method = "bayes.correlation",
  methodVersion = "1.0.1",
  title = "Bayesian correlation",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("BF₁₀ = %s (κ = %s), r = %s, ρ = %.2f, %s CrI [%.2f, %.2f]", cs_fmt_num(bf10), format(signif(kappa, 3)),
                cs_fmt_num(res$r, leading_zero = FALSE), post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high),
  statistics = list(
    list(key = "bf10", label = sprintf("BF₁₀ (%s vs ρ = 0)", direction), value = bf10),
    list(key = "bf01", label = "BF₀₁", value = 1 / bf10),
    list(key = "r", label = "Sample r", value = res$r),
    list(key = "rho", label = "ρ (posterior median)", value = post$median),
    list(key = "cri", label = sprintf("%.0f%% credible interval", 100 * cred), value = c(post$low, post$high))
  ),
  tables = list(list(key = "evidence", title = "Evidence",
    columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Value", type = "number")),
    rows = list(list(quantity = "BF₁₀ (chosen alternative)", value = bf10),
                list(quantity = "BF₁₀ (two-sided)", value = res$bf10_two_sided),
                list(quantity = "P(H₁ | data), equal prior odds", value = bf10 / (1 + bf10)),
                list(quantity = "Posterior mean of ρ", value = post$mean)))),
  effectSizes = list(list(key = "rho", label = "ρ (posterior median)", value = post$median, ciLow = post$low, ciHigh = post$high, ciLevel = cred,
                          method = "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(
    sprintf("Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = %s%s.", format(signif(kappa, 3)), if (alternative == "two-sided") "" else paste0(", restricted to ", direction)),
    sprintf("Evidence: %s. With equal prior odds, P(H₁ | data) = %.3f.", label, bf10 / (1 + bf10)),
    "A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger."
  ),
  values = list(
    bf10 = bf10, bf01 = 1 / bf10, log_bf10 = res$log_bf10, bf10_two_sided = res$bf10_two_sided, p_h1 = bf10 / (1 + bf10),
    r = res$r, n = n, kappa = kappa, rho_mean = post$mean, rho_median = post$median,
    rho_low = post$low, rho_high = post$high, error_pct = 100 * res$error,
    bf_robust_min = if (!is.null(res$robust_bf)) min(res$robust_bf) else NULL,
    bf_robust_max = if (!is.null(res$robust_bf)) max(res$robust_bf) else NULL
  ),
  charts = charts
))
Python

BF₁₀ = 9827186.99 (κ = 0.577), r = −.46, ρ = -0.45, 90% CrI [-0.55, -0.34]

BF₁₀ (ρ < 0 vs ρ = 0)
9.827e+6
BF₀₁
1.018e-7
Sample r
−0.4580
ρ (posterior median)
−0.4487
90% credible interval
[−0.5481, −0.3367]

Effect size

  • ρ (posterior median) −0.4487 90% CI [−0.5481, −0.3367]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
  • Linear relationship — Check the scatter plot: ρ measures linear association.
  • Independent observations — Each row should be a separate unit.

Evidence

QuantityValue
BF₁₀ (chosen alternative)9.827e+6
BF₁₀ (two-sided)4.914e+6
P(H₁ | data), equal prior odds1.0000
Posterior mean of ρ−0.4463
  • Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 0.577, restricted to ρ < 0.
  • Evidence: extreme evidence for H₁. With equal prior odds, P(H₁ | data) = 1.000.
  • A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec cbd627e00c0ffd94
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import bayes as bf  # Jeffreys correlation Bayes factor (twin of R cs_bayes_*)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Wind", "Temp"])
n_input = len(df)
df = df.dropna(subset=["Wind", "Temp"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Wind", "Temp"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
a, b = "Wind", "Temp"
x = df[a].to_numpy(dtype=float)
y = df[b].to_numpy(dtype=float)
if len(x) < 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A Bayesian correlation", min=3, n=len(x))
for column, v in ((a, x), (b, y)):  # exact check: a float SD of identical values need not be 0
    if len(np.unique(v)) < 2:
        cs.cs_error("CS_E_CONSTANT", column=column)
kappa = bf.prior_scale("correlation", "wide", 0.333)
alternative = "less"
cred = 0.9
res = bf.corr_bf(x, y, kappa=kappa, alternative=alternative, cred=cred,
                 robustness=True, sequential=True)
bf10 = res["bf10"]
post = res["post"]
n = len(x)

# %% Assumptions
assumptions = []
sw = [stats.shapiro(v).pvalue if 3 <= len(v) <= 5000 else None for v in (x, y)]
z = np.abs(stats.zscore(x)), np.abs(stats.zscore(y))
extreme = int(((z[0] > 3.5) | (z[1] > 3.5)).sum())
if extreme:
    status, detail = "warn", f"{extreme} row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them."
elif any(p is not None and p < 0.05 for p in sw) and n < 30:
    status, detail = "warn", "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
else:
    status, detail = "pass", "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
assumptions.append({"key": "normality", "label": "Bivariate normality", "status": status, "detail": detail})
assumptions.append({"key": "linearity", "label": "Linear relationship", "status": "info", "detail": "Check the scatter plot: ρ measures linear association."})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each row should be a separate unit."})

# %% Result
label = bf.evidence_label(bf10)
direction = {"two-sided": "ρ ≠ 0", "greater": "ρ > 0", "less": "ρ < 0"}[alternative]
summary = (
    f"BF₁₀ = {cs.fmt_num(bf10)} for a correlation between {a} and {b} (sample r = {res['r']:.2f}, n = {n}): "
    f"the data are {cs.fmt_num(bf10 if bf10 >= 1 else 1 / bf10)} times more likely under "
    f"{'the alternative (' + direction + ')' if bf10 >= 1 else 'no correlation'} — {label} (prior width κ = {kappa:.3g}). "
    f"Under the alternative, ρ is most likely near {post['median']:.2f} ({cred:.0%} credible interval [{post['low']:.2f}, {post['high']:.2f}])."
)
grid = res["grid"]
charts = [cs.chart(
    "prior_posterior", "prior-posterior", "Prior and posterior of ρ",
    {"x": cs.col("ρ", np.concatenate([grid, grid])),
     "density": cs.col("density", np.concatenate([res["prior_density"], res["posterior_density"]])),
     "curve": cs.col("curve", ["Prior"] * len(grid) + ["Posterior"] * len(grid), levels=["Prior", "Posterior"])},
    controls={"point": 0, "ci_low": post["low"], "ci_high": post["high"], "cred": cred, "bf10": bf10},
)]
if "robust_r" in res:
    charts.append(cs.chart("robustness", "bf-robustness", "Bayes factor across prior widths",
                           {"x": cs.col("prior width κ", res["robust_r"]), "bf": cs.col("BF₁₀", res["robust_bf"])}, controls={"chosen": kappa}))
if "seq_n" in res and len(res["seq_n"]) >= 2:
    charts.append(cs.chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
                           {"n": cs.col("rows", res["seq_n"]), "bf": cs.col("BF₁₀", res["seq_bf"])}))
rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts.append(cs.chart("scatter", "scatter", f"{b} against {a}", {"x": cs.col(a, x[rows]), "y": cs.col(b, y[rows])}))
cs.publish({
    "method": "bayes.correlation",
    "methodVersion": "1.0.1",
    "title": "Bayesian correlation",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"BF₁₀ = {cs.fmt_num(bf10)} (κ = {kappa:.3g}), r = {cs.fmt_num(res['r'], leading_zero=False)}, ρ = {post['median']:.2f}, {cred:.0%} CrI [{post['low']:.2f}, {post['high']:.2f}]",
    "statistics": [
        {"key": "bf10", "label": f"BF₁₀ ({direction} vs ρ = 0)", "value": bf10},
        {"key": "bf01", "label": "BF₀₁", "value": 1 / bf10},
        {"key": "r", "label": "Sample r", "value": res["r"]},
        {"key": "rho", "label": "ρ (posterior median)", "value": post["median"]},
        {"key": "cri", "label": f"{cred:.0%} credible interval", "value": [post["low"], post["high"]]},
    ],
    "tables": [{"key": "evidence", "title": "Evidence",
                "columns": [{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
                "rows": [{"quantity": "BF₁₀ (chosen alternative)", "value": bf10},
                         {"quantity": "BF₁₀ (two-sided)", "value": res["bf10_two_sided"]},
                         {"quantity": "P(H₁ | data), equal prior odds", "value": bf10 / (1 + bf10)},
                         {"quantity": "Posterior mean of ρ", "value": post["mean"]}]}],
    "effectSizes": [{"key": "rho", "label": "ρ (posterior median)", "value": post["median"], "ciLow": post["low"], "ciHigh": post["high"], "ciLevel": cred,
                     "method": "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = {kappa:.3g}{'' if alternative == 'two-sided' else ', restricted to ' + direction}.",
              f"Evidence: {label}. With equal prior odds, P(H₁ | data) = {bf10 / (1 + bf10):.3f}.",
              "A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger."],
    "values": {
        "bf10": bf10, "bf01": 1 / bf10, "log_bf10": res["log_bf10"], "bf10_two_sided": res["bf10_two_sided"], "p_h1": bf10 / (1 + bf10),
        "r": res["r"], "n": n, "kappa": kappa, "rho_mean": post["mean"], "rho_median": post["median"],
        "rho_low": post["low"], "rho_high": post["high"], "error_pct": 100 * res["error"],
        "bf_robust_min": float(np.min(res["robust_bf"])) if "robust_bf" in res else None,
        "bf_robust_max": float(np.max(res["robust_bf"])) if "robust_bf" in res else None,
    },
    "charts": charts,
})

The 90% credible interval runs from −0.55 to −0.34.

Now check the scatter plot and the assumption rows. Is the relationship linear? Do a few days pull it? A Bayes factor, however large, can't repair an outlier-driven correlation.

06

Check your understanding

Checkpoint

Check yourself

What happens to the prior on ρ\rho as κ\kappa shrinks?

Show the answer

Answer: b

κ=1\kappa = 1 is uniform. Smaller values say that small correlations are more plausible.

Check yourself

BF10\text{BF}_{10} = 2,000 with rr = 0.15 and nn = 800. Which statement can you defend?

Show the answer

Answer: b

The Bayes factor is about ρ≠0\rho \neq 0. The posterior for ρ\rho gives the size, and the design decides anything about cause.

Check yourself

With nn = 10, BF10\text{BF}_{10} = 1.2 and a posterior median of 0.44. What should you report?

Show the answer

Answer: c

The data are compatible with no correlation and with a large one, and you should say so.

07

Do it in CodeSplash

In the app

Choose First variable and Second variable, set the prior width and the direction, then read the robustness and sequential charts.

Python
import pandas as pd
import pingouin as pg

df = pd.read_csv("airquality.csv").dropna(subset=["Wind", "Temp"])
r = df["Wind"].corr(df["Temp"])
print(r, pg.bayesfactor_pearson(r, len(df), kappa=1.0))
R
# install.packages("BayesFactor")
library(BayesFactor)
correlationBF(airquality$Wind, airquality$Temp, rscale = "medium")

These scripts use their own priors and options, so the values may differ from the card's unless you match them.

08

Recap

Recap
  • The Bayesian correlation puts a stretched-beta prior on ρ\rho, with a width you state.
  • Few points give weak evidence, even for a large sample rr.
  • A huge Bayes factor doesn't mean a large correlation: read the posterior for size.
  • Check the plot, since a Bayes factor can't fix an outlier-driven relationship.

Concepts in this lesson