Skip to content

Instantly share code, notes, and snippets.

@AlexanderFabisch
Last active April 24, 2022 17:44
Show Gist options
  • Save AlexanderFabisch/7e3bce946ba70a5f1d221adbf30cda6f to your computer and use it in GitHub Desktop.
Save AlexanderFabisch/7e3bce946ba70a5f1d221adbf30cda6f to your computer and use it in GitHub Desktop.
Plot heart rate statistics per day from exported Garmin data.
"""
Plot heart rate statistics per day from exported Garmin data.
"""
import glob
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from fitparse import FitFile
timestamps = []
heartrates = []
for filename in list(glob.glob("*_WELLNESS.fit")):
fitfile = FitFile(filename)
msgs = list(fitfile.get_messages("monitoring"))
last_full_timestamp = None
for msg in msgs:
timestamp = msg.get_value("timestamp")
hr = msg.get_value("heart_rate")
if timestamp is not None:
timestamp = int(time.mktime(timestamp.timetuple()))
last_full_timestamp = timestamp
elif hr is not None and hr > 0:
assert last_full_timestamp is not None
timestamp_16 = msg.get_value("timestamp_16")
# https://www.thisisant.com/forum/viewthread/6374
timestamp = last_full_timestamp + ((timestamp_16 - (last_full_timestamp & 0xFFFF)) & 0xFFFF)
timestamps.append(timestamp)
heartrates.append(hr)
timestamps = np.asarray(timestamps, dtype=float)
heartrates = np.asarray(heartrates)
indices = np.argsort(timestamps)
timestamps = timestamps[indices]
heartrates = heartrates[indices]
df = pd.DataFrame({"timestamps": timestamps,
"heartrates": heartrates})
df["timestamps"] = pd.to_datetime(df["timestamps"], unit="s")
df.timestamps.dt.tz_localize("UTC").dt.tz_convert("Europe/Berlin")
df["day"] = df.timestamps.dt.floor("d")
sns.set_theme(style="ticks", palette="pastel")
sns.boxplot(x="day", y="heartrates", data=df)
sns.despine(offset=5, trim=True)
x_dates = df["day"].dt.strftime('%Y-%m-%d').sort_values().unique()
plt.gca().set_xticklabels(labels=x_dates, rotation=45, ha='right')
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment