Home > OS >  convert number (hours) to time (HH:MM) in x-axis in ggplot
convert number (hours) to time (HH:MM) in x-axis in ggplot

Time:11-18

Below is an example of readings taken in every 15 minutes from 6AM to 10PM.

How do I convert hours to time (HH:MM) in x-axis of ggplot

tbl <- tibble(x = seq(6, 22, 0.15),
              y = runif(n = 107))


ggplot(data = tbl,
       aes(x = x,
           y = y))   
  geom_line()   
  theme_bw()

CodePudding user response:

We may convert the 'x' to datetime with as_datetime from lubridate

library(dplyr)
library(ggplot2)
library(lubridate)
tbl %>% 
    mutate(x = as_datetime(hm(x))) %>%
    ggplot(aes(x = x, y = y))  
     geom_line()   
     theme_bw()   
     scale_x_datetime(breaks = "1 hour", date_labels =  "%H:%M")
  • Related