# add these two lines underneath the chunk where you have included the use_python line.
import os;
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:/ProgramData/Anaconda3/Library/plugins/platforms';
In this, we will be analyzing the Average Sleep Hours per day for Americans across the years 2003-2017. Our data contains information for the year, the average sleep hours per day, standard error, type of days, age group, and sex. We will be using most of these variables to analyze our data visually below.
Here are our findings:
Line Plot
import pandas as pd;
import numpy as np;
import seaborn as sns;
import matplotlib.pyplot as plt;
import warnings;
from matplotlib.ticker import FuncFormatter;
warnings.filterwarnings("ignore");
path = "U:/DS736 SP24/Time Americans Spend Sleeping.csv";
df = pd.read_csv(path);
year_df=df.groupby(df['Year'])['Avg hrs per day sleeping'].mean().reset_index();
min_index = year_df['Avg hrs per day sleeping'].idxmin();
max_index = year_df['Avg hrs per day sleeping'].idxmax();
plt.figure(figsize=(12, 6));
plt.plot(year_df['Year'], year_df['Avg hrs per day sleeping'], 'go', ls='-', ms=12, markevery=[min_index, max_index]);
plt.title('Average Sleep Hours by Year', fontsize=23);
plt.xlabel('Year', fontsize=18);
plt.ylabel('Average Sleep Hours', fontsize=18);
my_x_ticks = [*range(year_df['Year'].min(), year_df['Year'].max()+1, 1)];
plt.xticks(my_x_ticks, fontsize=14, color='black');
plt.xticks(rotation=45);
plt.annotate(f'Min: {year_df.loc[min_index, "Avg hrs per day sleeping"]:.3f}',
xy=(year_df.loc[min_index, 'Year'], year_df.loc[min_index, 'Avg hrs per day sleeping']),
xytext=(year_df.loc[min_index, 'Year'] - 1, year_df.loc[min_index, 'Avg hrs per day sleeping'] + 0.05),
arrowprops=dict(facecolor='black', arrowstyle='->'),fontsize=14);
plt.annotate(f'Max: {year_df.loc[max_index, "Avg hrs per day sleeping"]:.3f}',
xy=(year_df.loc[max_index, 'Year'], year_df.loc[max_index, 'Avg hrs per day sleeping']),
xytext=(year_df.loc[max_index, 'Year'] - 1, year_df.loc[max_index, 'Avg hrs per day sleeping'] - 0.05),
arrowprops=dict(facecolor='black', arrowstyle='->'),fontsize=14);
plt.tight_layout();
plt.show()
Seen above, the year 2004 with an average of 8.678 sleep hours is our data’s minimum average sleep hours per day across the years 2003-2017. Contrarily, the year 2015 contains the maximum average sleep hours across those years with an average of 8.937 hours per day. We can see that there’s not a whole lot of variances among the average sleep hours in our data. For instance, the y-axes only go from 8.70 to 8.90 and all average sleep hours fall within those parameters.
Double Bar Chart
# I added these two lines as I had some errors when knitting my rmarkdown code
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'c:/users/pptallon/Anaconda3/Library/plugins/platforms'
agg_df = df.groupby(df['Year']).agg({"Avg hrs per day sleeping": "mean", "Standard Error": "mean"})
fig, ax = plt.subplots(figsize=(18,10))
bar_width = 0.5
opacity = 0.8
index = agg_df.index
bar1 = ax.bar(index - bar_width/2, agg_df["Avg hrs per day sleeping"], bar_width, color='teal', edgecolor='black',label='Average', alpha=opacity)
bar2 = ax.bar(index + bar_width/2, agg_df["Standard Error"], bar_width, color='orange', edgecolor='black', label='Standard Error', alpha=opacity)
ax.set_xlabel('Year', fontsize=26)
ax.set_ylabel('Count', fontsize=26)
ax.set_title('Average and Standard Error of Sleep Hours by Year', fontsize=32)
ax.set_xticks(index)
ax.legend(bbox_to_anchor=(0, 1), loc='upper right', fontsize=16)
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
for bar in bar1 + bar2:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
'%.2f' % height,
ha='center', va='bottom', fontsize=16)
plt.tight_layout()
plt.show()
In this graph, we created a double bar chart to show both the average sleep hours and their standard error for each year. Similar to our line plot, there’s not a ton of variance among these statistics which is why all the bars look almost equal. For this reason, I decided to label each bar with their corresponding value to illustrate the differences although not very big. What we can see is that both the average and the standard error increased as the years went by though not by a lot.
Pie Chart
age_df = df.groupby('Age Group')['Avg hrs per day sleeping'].mean().reset_index()
plt.figure(figsize=(10, 8))
plt.pie(age_df['Avg hrs per day sleeping'], labels=age_df['Age Group'],autopct='%1.2f%%')
plt.title('Average Sleep Hours by Age Group',fontsize=17)
plt.legend(loc='lower right', fontsize=7)
plt.show()
This pie chart is measuring the average sleep hours by the age groups provided in our data. The slices have their label to show which group is being presented as well as the percentage of the pie that this slice takes up. I included a legend as well to show which colors represent which age groups. The pie chart shows the age group of 15 to 24 years has the largest slice of 15.41% showing they have the highest average of sleep hours across all of the age groups. This makes sense as this age group is in their adolescence and early adulthood which may imply, they have more free time.
Heatmap
days_df = df.groupby(['Type of Days', 'Age Group'])['Avg hrs per day sleeping'].mean().reset_index()
heatmap_data = days_df.pivot('Type of Days', 'Age Group', 'Avg hrs per day sleeping')
yticklabels = ['All Days', 'Nonholiday Weekdays', 'Weekend Days']
plt.figure(figsize=(14,10))
ax = sns.heatmap(heatmap_data, annot=True, cmap='coolwarm', fmt=".1f", yticklabels=yticklabels)
plt.title('Average Sleep Hours by Age Group and Type of Days',fontsize=16)
plt.xlabel('Age Group',fontsize=14)
plt.ylabel('Type of Days',fontsize=14)
plt.yticks(rotation=45)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
This visualization turned out being my favorite due to its visual appeal. Seen above, we have the Type of Days on the y-axis and the Age Groups on our x-axis and we’re illustrating the highest average sleep within the age groups and type of days. A legend has been included on the right to show that the blue-shaded areas represent our lower sleep averages and the red-shaded areas represent our higher sleep averages. What I found to be really cool was that it’s very apparent the highest sleep averages belongs to those in the 15 to 24 years age group and this typically takes place on weekend days. We can infer this because the shaded area for those groups is dark red and I made sure to include data labels and this one shows an average of 10.1 sleep hours per day.
Comparative Boxplot
plt.figure(figsize=(12, 8))
medians = df.groupby('Sex')['Avg hrs per day sleeping'].median().round(2)
box_width = 0.4
for i, median in enumerate(medians):
plt.text(i - box_width/2, median, f'{median}', ha='center',va='bottom', fontsize=12, color='black')
sns.boxplot(x='Sex', y='Avg hrs per day sleeping', data=df,palette='Set3')
plt.title('Average Sleep Hours by Sex', fontsize=18)
plt.xlabel('Sex',fontsize=15)
plt.ylabel('Average Sleep Hours',fontsize=15)
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()
Lastly, we have a comparative box plot analyzing the average sleep hours across our sex variable within our data. This data included Men, Women, and Both within the sex variable and so I included all three within my plot. I also made sure to include the mean of each sex on their corresponding box near the center line as that is what represents the average. At a glance, we can see that women have a higher average of sleep hours than men with the women’s average of 8.85 and the men’s average of 8.73. Again, not a super significant difference but one I was curious about.
In conclusion, we can certainly take away that there’s not a whole lot of variance or difference within our average sleep hours BUT it can still tell a story. I’m walking away knowing that this data shows an increase of average sleep hours from 2003 to 2017 with its peak in 2015. I also interpreted that those averages, likewise, have low standard errors that do not contain a lot of variances. In closing, the highest average of sleep hours typically takes place on weekend days, by the 15 to 24 years age group, and primarily by women.