Search code examples
rdatetimelubridateposixct

Remove date element from datetime while making line graph in r


I have a data frame containing the average steps count of various people by hours of the day. I used the POSIXct function to render by-hour data in date-time readable form, but the function automatically assigns today's date to my variables. I want to create a line graph by ggplot and I don't want the labels to show the date as well.

av_steps_by_hour$time = as.POSIXct(av_steps_by_hour$time, format = "%H:%M:%S")
ggplot(data = av_steps_by_hour) + geom_line(aes(x = time, y = steps))

enter image description here


Solution

  • You can format the dates/times before plotting (as ViviG shows), or specify the format using the scale_x_datetime() function, e.g.

    library(tidyverse)
    av_steps_by_hour = data.frame(time = as.POSIXct(c("00:00:00", "06:00:00", "12:00:00", "18:00:00"),
                                                    format = "%H:%M:%S", origin = "1970-01-01"),
                                  steps = c(1000, 1001, 1010, 1500))
    # 'Before'
    ggplot(data = av_steps_by_hour) +
      geom_line(aes(x = time, y = steps))
    

    # 'After'
    ggplot(data = av_steps_by_hour) +
      geom_line(aes(x = time, y = steps)) +
      scale_x_datetime(date_labels = "%H:%M:%S")
    

    Created on 2022-08-18 by the reprex package (v2.0.1)