Remove date element from datetime while making line graph in r

Viewed 32

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

2 Answers

You need to first convert the data to POSITXct, then format it.

First convert the data

now <- as.POSIXlt(Sys.time())) 

Then format it

format(now, "%H:%M:%S")
[1] "07:52:30"

Here is a reproducible example:

library(ggplot2)

av_steps_by_hour = data.frame(time = (Sys.time()), steps = c(1:4))

av_steps_by_hour$time = as.POSIXct(av_steps_by_hour$time)

av_steps_by_hour$time = format(av_steps_by_hour$time, "%H:%M:%S")

ggplot(data = av_steps_by_hour) + geom_line(aes(x = time, y = steps))

enter image description here

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)

Related