ipywidget-example.ipynb
how to use the ipywidgets together with a matplotlib plot
I was wondering: How similar are the sleep time measures that my Fitbit Versa and my Oura ring report as I have plenty of nights where I've been wearing both devices. To find out I wanted to run a quick correlation with the data stored in Open Humans.
To run this notebook you need to have data from both the Fitbit Connection and the Oura connect Open Humans projects in your account.
Let's load the data from both data sources in a first step:
Now we can throw the data in one joined data structure for doing the plotting. We limit the analysis for data from 2018 and 2019 as these are the only years in which I have data for both devices from the same nights.
As you can see we have a table with two columns: The minutes of sleep for Fitbit and Oura. With this we can now plot the data:
I was wondering: How similar are the sleep time measures that my Fitbit Versa and my Oura ring report as I have plenty of nights where I've been wearing both devices. To find out I wanted to run a quick correlation with the data stored in Open Humans.
To run this notebook you need to have data from both the Fitbit Connection and the Oura connect Open Humans projects in your account.
Let's load the data from both data sources in a first step:
from ohapi import api
import os
import requests
import json
from collections import defaultdict
import datetime
import matplotlib.pyplot as plt
from numpy.polynomial.polynomial import polyfit
user_details = api.exchange_oauth2_member(os.environ.get('OH_ACCESS_TOKEN'))
for i in user_details['data']:
if i['source'] == 'direct-sharing-184' and i['basename'] == 'oura-data.json':
oura = json.loads(requests.get(i['download_url']).content)
if i['basename'] == 'fitbit-data.json' and i['source'] == 'direct-sharing-102':
fitbit_data = requests.get(i['download_url']).json()
Now we can throw the data in one joined data structure for doing the plotting. We limit the analysis for data from 2018 and 2019 as these are the only years in which I have data for both devices from the same nights.
sleep_data = defaultdict(dict)
for sleep in oura['sleep']:
if (sleep["summary_date"][:4] == "2019") or sleep["summary_date"][:4] == "2018":
date = sleep['summary_date']
sleep_data[date]['oura'] = sleep['total']/60
for sleep in fitbit_data['sleep-minutes']['2019']['sleep-minutesAsleep']:
sleep_data[sleep['dateTime']]['fitbit'] = sleep['value']
for sleep in fitbit_data['sleep-minutes']['2018']['sleep-minutesAsleep']:
sleep_data[sleep['dateTime']]['fitbit'] = sleep['value']
date = []
oura_values = []
fitbit = []
for k,v in sleep_data.items():
date.append(k)
if 'oura' in v.keys():
oura_values.append(v['oura'])
else:
oura_values.append(None)
if 'fitbit' in v.keys():
fitbit.append(v['fitbit'])
else:
fitbit.append(None)
import pandas as pd
dataframe_naive = pd.DataFrame(
data = {
'date': date,
'oura': oura_values,
'fitbit': fitbit
}
)
sleep_data = defaultdict(dict)
for sleep in oura['sleep']:
if (sleep["summary_date"][:4] == "2019") or sleep["summary_date"][:4] == "2018":
date = sleep['summary_date']
date = date.split("-")
date = [int(i) for i in date]
date = datetime.date(year=date[0],month=date[1],day=date[2]) + datetime.timedelta(days=1)
sleep_data[date.strftime(format="%Y-%m-%d")]['oura'] = sleep['total']/60
for sleep in fitbit_data['sleep-minutes']['2019']['sleep-minutesAsleep']:
sleep_data[sleep['dateTime']]['fitbit'] = sleep['value']
for sleep in fitbit_data['sleep-minutes']['2018']['sleep-minutesAsleep']:
sleep_data[sleep['dateTime']]['fitbit'] = sleep['value']
date = []
oura_values = []
fitbit = []
for k,v in sleep_data.items():
date.append(k)
if 'oura' in v.keys():
oura_values.append(v['oura'])
else:
oura_values.append(None)
if 'fitbit' in v.keys():
fitbit.append(v['fitbit'])
else:
fitbit.append(None)
dataframe_offset = pd.DataFrame(
data = {
'date': date,
'oura': oura_values,
'fitbit': fitbit
}
)
dataframes = {'naive': dataframe_naive, 'offset': dataframe_offset}
As you can see we have a table with two columns: The minutes of sleep for Fitbit and Oura. With this we can now plot the data:
def plot_results(dataframe):
dataframe['fitbit'] = pd.to_numeric(dataframe['fitbit'])
dataframe_sub = dataframe[dataframe['fitbit'] > 100]
dataframe_sub = dataframe_sub[dataframe['oura'] > 0]
b, m = polyfit(dataframe_sub['oura'], dataframe_sub['fitbit'], 1)
plt.scatter(dataframe_sub['oura'],dataframe_sub['fitbit'], alpha=0.3)
plt.plot(dataframe_sub['oura'], b + m * dataframe_sub['oura'], '-')
plt.title('Oura vs Fitbit sleep duration')
plt.xlabel('Oura (minutes of sleep)')
plt.ylabel('Fitbit (minutes of sleep)')
plt.show()
import ipywidgets as widgets
from IPython.display import clear_output
def handle_dropdown_change(change):
if change.new != '--':
clear_output()
plot_results(dataframes[change.new])
display(dropdown)
dropdown = widgets.Dropdown(
options=['--','naive', 'offset'],
value='--',
description='Plot type:',
disabled=False,
)
dropdown.observe(handle_dropdown_change, names='value')
display(dropdown)