# Q-29: Median and spread of ten trials

Data-Driven Athletics tutorial · Week 10 · Chapter 10 · about 15 min · workflow steps: Gather, Statistics, Visualize

Web page: https://apopt.com/course/tutorials/q29-ten-trials/ · Data: https://apopt.com/data/tutorials/q29-ten-trials/

## The decision

A shooter wants one number for "my release angle" to train against. From ten shots, which
summary should it be, and how much spread is normal for this shooter?

## The raw data

- `raw/results/results_shot01.md`: one of ten SYNTHETIC basketball results files (results_shot01.md to results_shot10.md) in the layout of the apps' text results, made with a fixed random seed Chapter 10's synthetic example data (`book/ch10-skill/data/results/`), made by `code/make_synthetic_results.py`. Not a measurement of anyone.
- `raw/shot_log.csv`: the SYNTHETIC made-or-missed log, one row per shot Same source.

One shot is an anecdote; ten shots are a sample (Section 10.6). The raw files are ten results
files in the layout the basketball app writes, one per shot, and the made-or-missed log the
shooter kept by hand. **They are synthetic**: Chapter 10 made them with a fixed random seed so
that everyone gets the same numbers. They are not measurements of anyone.

*Predict first:* Ten shots by one shooter: how many degrees apart do you expect the lowest and highest release angle to be?

```python
import glob
import re
import pandas as pd

rows = []
for f in sorted(glob.glob("raw/results/results_*.md")):
    for line in open(f, encoding="utf-8").read().splitlines():
        cells = [c.strip() for c in line.strip("|").split("|")]
        if len(cells) == 5 and cells[0] not in ("Section", "---"):
            num = re.search(r"[-+]?\d+(\.\d+)?", cells[2])      # "46.3 °" -> 46.3
            rows.append({"file": f.split("/")[-1], "metric": cells[1], "value": float(num.group())})
trials = pd.DataFrame(rows).pivot(index="file", columns="metric", values="value")
trials = trials.join(pd.read_csv("raw/shot_log.csv").set_index("file")["made"])
print(trials.to_string())
```

Output:

```
                   Ball Release Angle  Ball Release Height  Elbow Angle  Knee Flexion  Release Timing vs Apex  made
file                                                                                                               
results_shot01.md                46.3                 1.07        159.0          97.0                   -23.0     1
results_shot02.md                48.8                 1.10        160.0         105.0                   -25.0     1
results_shot03.md                43.0                 1.03        158.0         102.0                   -17.0     0
results_shot04.md                46.2                 1.09        157.0          92.0                   -15.0     1
results_shot05.md                46.5                 1.06        161.0          97.0                   -22.0     1
results_shot06.md                40.8                 1.04        162.0         109.0                     3.0     0
results_shot07.md                48.0                 1.04        157.0         102.0                   -19.0     1
results_shot08.md                47.6                 1.05        160.0         105.0                    -8.0     0
results_shot09.md                47.2                 1.07        160.0         105.0                   -26.0     1
results_shot10.md                46.8                 1.05        160.0          97.0                    -7.0     0
```

### Center and spread, two ways

The **mean** and **standard deviation** use every value's size, so one wild value moves them.
The **median** and the **interquartile range** (IQR, the middle half) or the **median absolute
deviation** (MAD, the median distance from the median) do not. The disc app scales the MAD by
1.4826 (`disc/src/lib/metric-registry.ts`), which turns it into a robust standard deviation:
for normal scatter the raw MAD is only about two thirds of one.

```python
import numpy as np

def robust(v):
    med = np.median(v)
    q1, q3 = np.percentile(v, [25, 75])
    mad = np.median(np.abs(v - med))
    return pd.Series({"mean": v.mean(), "SD": v.std(ddof=1), "median": med, "IQR": q3 - q1,
                      "MAD": mad, "1.4826 MAD": 1.4826 * mad})

summary = trials.drop(columns="made").apply(robust).T
print(summary.round(2).to_string())
angle = trials["Ball Release Angle"]
print(f"release angle without its lowest shot: mean {angle.drop(angle.idxmin()).mean():.2f}, "
      f"median {angle.drop(angle.idxmin()).median():.2f}")
```

Output:

```
                          mean    SD  median    IQR   MAD  1.4826 MAD
Ball Release Angle       46.12  2.42   46.65   1.27  0.75        1.11
Ball Release Height       1.06  0.02    1.06   0.03  0.02        0.02
Elbow Angle             159.40  1.65  160.00   1.75  1.00        1.48
Knee Flexion            101.10  5.20  102.00   8.00  4.00        5.93
Release Timing vs Apex  -15.90  9.33  -18.00  13.00  6.00        8.90
release angle without its lowest shot: mean 46.71, median 46.80
```

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 2.6))
q1, q3 = np.percentile(angle, [25, 75])
ax.axvspan(q1, q3, color="gray", alpha=0.25, label="middle half (IQR)")
ax.axvline(angle.median(), color="black", lw=2, label="median")
ax.axvline(angle.mean(), color="black", ls="--", lw=1, label="mean")
made = trials["made"] == 1
ax.plot(angle[made], np.zeros(made.sum()), "o", ms=9, color="black", label="made")
ax.plot(angle[~made], np.zeros((~made).sum()), "o", ms=9, mfc="white", color="black", label="missed")
ax.set(xlabel="ball release angle (degrees, synthetic)", yticks=[])
ax.legend(loc="upper left", fontsize=7, ncol=3)
plt.tight_layout()
```

![The ten release angles as dots along one axis, filled for made shots and open for missed ones, with a solid line at the median, a shaded band for the interquartile range and a dashed line at the mean.](https://apopt.com/course/tutorials/q29-ten-trials/c04-1.png)

Eight of the ten release angles sit between 46.2° and 48.8°; two missed shots, 40.8° and
43.0°, sit well below. Those two pull the mean (46.12°) below the median (46.65°) and more than
double the standard deviation (2.42°) compared with the robust spread (1.4826 × MAD = 1.11°).
Drop the lowest shot and the mean jumps by 0.59° while the median moves by 0.15°. That is why
the apps build a personal baseline from medians and MADs: one bad shot, or one frame where the
ball was lost, should not move the target. The low shots are not errors to delete, though;
both were misses, and CS-14 asks whether release angle separates makes from misses.

**For the athlete:** your release angle is about 46.7°, give or take about 1°; judge the next
session's ten shots against that, not against your best shot.

## With your own data

Save the text results of ten of your own clips from one app, in one folder, keep a
made-or-missed log, and run the first cell on that folder.

## The same method in another field

Robust summaries are the standard for any repeated measurement with occasional bad readings:
ten readings of a gauge, a sensor with dropouts, lab replicates.

## Acknowledgements

Synthetic results files from Chapter 10 of *Data-Driven Athletics*.

## References

- Chapter 10 of *Data-Driven Athletics*: Many Trials; Medians and spread.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
