SiH
SiH

Reputation: 1546

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

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()

Upvotes: 2

Views: 839

Answers (1)

akrun
akrun

Reputation: 887118

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")

Upvotes: 3

Related Questions