Home > OS >  ggplot line graph with days on x-axis and clock time on y-axis
ggplot line graph with days on x-axis and clock time on y-axis

Time:09-17

I want to illustrate mean sleep times per day grouped by different survey phases (T1, T2, T3). Here is an example of what my dataframe looks like:

structure(list(code = c("AJH27", "AJH27", "AJH27", "AJH27", "AJH27", 
"AJH27"), slt = c("22:10:00", "21:22:00", "22:00:00", "21:50:00", 
"20:55:00", "21:55:00"), day = c("Mi", "Do", "Fr", "Sa", "So", 
"Mo"), tmp = c("T1", "T1", "T1", "T1", "T1", "T1")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

The orginal datasets consists the data of more than three observations. Now I want to create a line graph, with the days (Mo to So) on the x-axis showing the mean sleep time for each day of the survey phase (clock time on y-axis). This would include three different lines (colored by group).

I not very experienced using ggplot and I could not figure out how to build the graph I want.

EDIT:

This is what my graph looks like when I used your code @JonSpring

enter image description here

CodePudding user response:

Here's an approach using lubridate::hms to convert the H:M:S text into a time period (in seconds) and then convert that to hours.

library(dplyr); library(lubridate); library(ggplot2)

# convert day into an ordered factor so it displays in the right order
dat$day = factor(dat$day, ordered = TRUE,
                     levels = c("Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"))

dat %>%
  mutate(hours = as.numeric(hms(slt))/(60*60)) %>%
  ggplot(aes(day, hours, color = tmp, group = tmp))  
  geom_line()

enter image description here

EDIT: alternatively, to use a timestamp for the y axis:

dat %>%
  mutate(hours = ymd_hms(paste("20000101", slt))) %>%
  ggplot(aes(day, hours, color = tmp, group = tmp))  
  geom_line()

enter image description here

  • Related