Skip to content

Instantly share code, notes, and snippets.

@fraga
Last active February 24, 2023 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fraga/68078c196844a3a9a2d25181fc19b3fd to your computer and use it in GitHub Desktop.
Save fraga/68078c196844a3a9a2d25181fc19b3fd to your computer and use it in GitHub Desktop.
Sleep.py
import io
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Define the input CSV string
csv_string = """timestamp,duration
2022-02-20 23:00:00,420
2022-02-21 00:30:00,300
2022-02-21 07:15:00,360
2022-02-22 01:00:00,420
2022-02-22 06:30:00,240
2022-02-23 00:45:00,360
2022-02-23 06:30:00,420
"""
# Load the sleep data
sleep_data = pd.read_csv(io.StringIO(csv_string))
# Preprocess the data
sleep_data['date'] = pd.to_datetime(sleep_data['timestamp']).dt.date
sleep_data['start_time'] = pd.to_datetime(sleep_data['timestamp']).dt.time
sleep_data['end_time'] = pd.to_datetime(sleep_data['timestamp'] + pd.to_timedelta(sleep_data['duration'], unit='m')).dt.time
# Aggregate the data
daily_sleep = sleep_data.groupby('date').agg(
total_sleep=('duration', 'sum'),
start_time=('start_time', 'min'),
end_time=('end_time', 'max')
)
# Calculate the polar coordinates
theta = np.linspace(0, 2 * np.pi, len(daily_sleep), endpoint=False)
r = daily_sleep['total_sleep'] / 60
# Plot the chart
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='polar')
ax.plot(theta, r, color='black', linewidth=3)
ax.fill(theta, r, facecolor='black', alpha=0.1)
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_rlim(0, 8)
ax.set_rlabel_position(105)
ax.set_xticklabels(['12am', '', '', '', '', '', '6am', '', '', '', '', '', '12pm', '', '', '', '', '', '6pm', '', '', '', '', ''])
ax.set_title('Sleep Pattern', fontsize=18, pad=20)
# Add vinyl disk-like styling
ax.spines['polar'].set_visible(False)
ax.grid(linestyle='--', alpha=0.8)
ax.text(0.5, 1.05, 'Sleep Vinyl', transform=ax.transAxes, fontsize=24, ha='center')
ax.text(0.5, 1.01, 'Amount of sleep (hours)', transform=ax.transAxes, fontsize=16, ha='center')
ax.annotate('', xy=(np.pi, 8), xytext=(0, 8),
arrowprops=dict(facecolor='black', arrowstyle='<|-', lw=1.5, alpha=0.8))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment