R语言时间系列作图

努力尽今夕,少年犹可夸。

Posted by Chevy on March 24, 2021

自我督促早点睡觉

Nicole最近最近和我发起了一项早睡早起的健康活动。

为了持续记录我的入睡时间,花了一小时造了个轮子,予以记录。

其实写的非常的琐碎,很多地方完全没有考虑逻辑优化,不过R语言还要啥优化啊,出图就行。

sleep.md.png

后续待更新:

  1. 添加时间区域图片(明早组会的时候摸鱼找几张)
  2. scale到月份进行统计
  3. 争取全自动化录入+输出作图
  4. 如有还有精力的话,开发成shiny托管到vps上

代码

library(tidyverse)

testdf <- data.frame(DateTime = rep(seq.POSIXt(as.POSIXct("2021-03-20 00:00"),
                                               by = "day", length.out = 5), each =2),
                     SleepTime = c(
                       as.POSIXct("23:59",format = "%H:%M") + 60*63, as.POSIXct("23:59",format = "%H:%M") + 60*108,
                       as.POSIXct("23:59",format = "%H:%M") + 60*116, as.POSIXct("23:59",format = "%H:%M") + 60*301,
                       as.POSIXct("23:59",format = "%H:%M") + 60*11, as.POSIXct("23:59",format = "%H:%M") + 60*7,
                       as.POSIXct("23:59",format = "%H:%M") + 60*51, as.POSIXct("23:59",format = "%H:%M") + 60*91,
                       as.POSIXct("23:59",format = "%H:%M") + 60*10, as.POSIXct("23:59",format = "%H:%M") + 60*10
                     ),
                     People = rep(c("Nicole", "Chevy")))

ggplot(testdf, aes(x = DateTime, y = SleepTime)) + 
  geom_rect(ymin = as.POSIXct("20:30", format = "%H:%M") + 3600*5, 
            ymax = as.POSIXct("20:30", format = "%H:%M") + 3600*10, 
            xmin = -Inf, xmax = Inf, 
            fill = "#303F9F", alpha = 0.05, colour = NA) +
  geom_rect(ymin = as.POSIXct("20:30", format = "%H:%M") + 3600*3, 
            ymax = as.POSIXct("20:30", format = "%H:%M") + 3600*5, 
            xmin = -Inf, xmax = Inf, 
            fill = "#8BC34A", alpha = 0.05, colour = NA) + 
  geom_rect(ymin = as.POSIXct("20:30", format = "%H:%M"), 
            ymax = as.POSIXct("20:30", format = "%H:%M") + 3600*3, 
            xmin = -Inf, xmax = Inf, 
            fill = "light pink", alpha = 0.1, colour = NA) +
  geom_point(aes(color = People), size = 2) + 
  geom_line(aes(color = People), size = 1) + 
  scale_y_datetime(date_breaks = "1 hour", date_labels= "%H:%M", expand = c(0,0),
                   limits = c(seq.POSIXt(as.POSIXct("20:30", format = "%H:%M"), by = "10 hour", length.out = 2))) +
  scale_x_datetime(date_labels = "%d") +
  theme_classic() +
  theme(legend.position = c(0.9, 0.9), 
        legend.background = element_rect(fill=alpha('#303F9F', 0))) +
  labs(title="Record for Sleep", 
       subtitle="Dispel Dark Energy", 
       caption="Created by Nicole", 
       x="March",
       y="Bed time", 
       color=NULL) +
  scale_color_manual(labels = c("Chevy", "Nicole"), 
                     values = c("Chevy"="#00ba38", "Nicole"="#f8766d"))

ggsave("sleep.png", width = 6, height = 5)