Visualising sleep with python and matplotlib from health data

Karthik Mahendra
4 min readDec 18, 2019

iPhone Health gives spectacular visualization of your sleep, steps, walked distance, so on. If you are a geek then try digging up distinct visualizations exploiting the Health app data. Here I extracted the data from Health App to display how many hours I slept on an average in a week throughout the year. I will explain here, how to bring in visualization as displayed below and more using Python programming.

Average Hours Slept in a week

Before that the data has to be collected, years of data from your iPhone can be utilized to have such a beautiful visualization. The data is in the form of .XML which is difficult to get the visualizations, converting it to CSV(Comma Separated Values) file could solve the issue. One way to get the data is by following steps later in the article or directly downloading the CSV file using Health data Importer app. Well, I was a bit lazy, so I installed the app and downloaded the CSV file.

Exporting the Health data using the iPhone health app

Step-1: Open your Health app on iPhone.

Health app as seen on iPhone

Step-2: On top right corner of the screen, click on your profile.

Step-3: Now click on “Export Health Data” and then “Export” to export the health data file.

Select “Export Health Data”
Select “Export” to export all the data

Step-4: Wait, while it starts preparing the .zip file and then to use the file, export it to either Files app(on iPhone), Google Drive, or even mail it to yourself, whichever provides you the convenient access.

Uploading the data to Google Drive

Step-5: You can find the XML file when you unzip the ‘export.zip’ file

Programming the Health app Data

Once you have your exported the data, convert it into a .CSV (convert it online using online CSV converter)file if the file is not in .CSV and then rename the file as “SleepAnalysis” (you can give any name to it, don’t forget to change name while reading it in the code file).

Its time for some programming. Run the following the code in Jupiter Notebooks or in the Python shell.

You can see something like this.

Program Code

You might get the graph, well what does the code tell. The code is available in github.

Getting started with the code, I loaded the “SleepAnalysis.csv” file into dataframe(df).

import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
df=pd.read_csv('SleepAnalysis.csv')

“.Timestamp” converts into machine-readable time format. The week day is then extracted from the dataframe “df” into a variable “day”. For more information regarding “Timestamp” refer the documentation here.

day=list(map(lambda n : pd.Timestamp(n).day_name(),df['In bed start']))
df['Hours in bed']=list(map(lambda h:h//60 ,df['Minutes in bed'].tolist()))
df['Day']=day
val=df.groupby('Day')['Hours in bed'].mean()

Now its time to plot the graph. Here I used “matplotlib” library to plot the bar graph. For information regarding the plots using matplotlib refer here.

plt.bar(val.index.to_list(),val,width=.45)
plt.xlabel('Days')
plt.ylabel('Hours')
plt.title('Average Hours Slept in week')

Related resources:

Further, try implementing the following using Python programming-

  1. On a specific day(say 10 January 2018) How many hours did you sleep?
  2. What is the average time you go to the bed every day?
  3. Get the days when you slept for a specific time(say 4 hours)

--

--