"""Q-37: One chart that makes one point -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q37-one-chart/
Data:     https://apopt.com/data/tutorials/q37-one-chart/ (keep raw/ next to this file)
"""

# %% [markdown]
# A chart in a report has a few seconds of the reader's attention. Section 13.5 turns the
# research on how people read charts into five rules: one message, and it is the title; the
# athlete's own baseline as the reference; the single trials as well as the means; meaning that
# does not depend on color; and no more digits on the axis than the measurement supports.
#
# The data are Chapter 13's **teaching set**: fifteen 20-second clips of a runner, Quinn, on a
# treadmill, three clips a session, before, during and after three weeks of running to a
# metronome. The coach's question: did the step rate rise, and did it last?
#
# ### Open the table

# %%
# Fifteen clips, five sessions
import pandas as pd

df = pd.read_csv("raw/cadence_sessions_synthetic.csv")
print(df.groupby(["day", "phase"])["cadence_spm"].agg(["count", "mean", "std"]).round(1).to_string())
base = df[df["phase"] == "baseline"]["cadence_spm"]
print(f"baseline: mean {base.mean():.1f}, SD {base.std():.2f} steps a minute")

# %% [markdown]
# ### The first chart, and the one-point chart
#
# On the left is what a plotting tool draws by default: every clip in file order, joined by a
# line, titled with the column name. On the right is the same data drawn to the fixed template
# of Section 13.5.1.

# %%
# A default chart and a chart with one message
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

m, te = base.mean(), base.std()
day = df.groupby(["day", "phase"], as_index=False)["cadence_spm"].mean()
fig, (a, b) = plt.subplots(1, 2, figsize=(8.0, 2.9))
a.plot(df["cadence_spm"])                                         # the default
a.set_title("cadence_spm")
b.axhspan(m - 2 * te, m + 2 * te, color="0.88", lw=0)              # the athlete's own usual range
b.text(df["day"].max(), m, "your usual range\n(days 1-4)", ha="right", va="center", fontsize=8)
b.plot(df["day"], df["cadence_spm"], ".", color="0.6", ms=5)        # every clip
b.plot(day["day"], day["cadence_spm"], "-o", color="0.1", ms=5)     # each day's mean
mt = day[day["phase"] == "metronome"].iloc[0]
b.annotate("with metronome", (mt["day"], mt["cadence_spm"]), xytext=(8, -12), textcoords="offset points", fontsize=8)
b.set(xlabel="day", ylabel="steps per minute")
b.set_title("Step rate rose about 6 a minute and held without the beat", fontsize=9)
b.yaxis.set_major_locator(MaxNLocator(integer=True))               # no false digits
plt.tight_layout()
print(f"band: {m:.1f} ± {2 * te:.1f} steps a minute")

# %% [markdown]
# The default chart has no message, no reference, and an x axis in rows rather than days, so
# the reader cannot see the metronome or the gap of two weeks. The right-hand chart answers the
# coach's question before the reader has read the axes: the last two sessions sit above the
# band of Quinn's usual range, and the gray dots show that this is not one lucky clip.
#
# **For the athlete:** "Your step rate on easy runs went from about 157 to about 163 a minute,
# and it stayed there after we stopped the beat."
