[R] How to plot dates

Jeff Reichman re|chm@nj @end|ng |rom @bcg|ob@|@net
Fri Mar 19 03:53:34 CET 2021


Greg

 

Based upon you last email I suspect this is what you were looking for.

 

# create the data.frame

datetime <- c("2021-03-12 05:16:46","2021-03-12 09:17:02","2021-03-12
13:31:43","2021-03-12 22:00:32",

              "2021-03-13 09:21:43","2021-03-13 13:51:12","2021-03-13
18:03:13","2021-03-13 22:20:28",

              "2021-03-14 08:59:03","2021-03-14 13:15:56","2021-03-14
17:25:23","2021-03-14 21:36:26")

group_id <- rep(1:4, 3)

myDat <- data.frame(datetime, group_id)

myDat

 

# library

library(ggplot2)   # package used to plot results

library(lubridate) # package used to extract the "dates"

 

# convert data to date time object

myDat$datetime <- as.POSIXct(myDat$datetime, tz = "", format = "%Y-%m-%d
%H:%M:%S")

 

# extract time

myDat$time <- strftime(myDat$datetime, format = "%H:%M:%S")

 

# convert time to seconds

myDat$seconds <- seconds(hms(myDat$time))

 

# extract date

myDat$dates <- as.Date(ymd_hms(myDat$datetime))

 

# plot results by datetime  

ggplot(data = myDat, aes(x = dates, y = seconds, group = group_id, colour =
factor(group_id)))+

  geom_line() +

  geom_point() +

  # Rotate and adjust x axis text

  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +

  labs(title = "Event Time (seconds) verse Date", x = "Date", y = "Time
(seconds)") +

  scale_colour_discrete(name="Group ID",

                        breaks=c("1", "2", "3", "4"),

                        labels=c("Gp 1", "Gp 2", "Gp 3", "Gp 4"))


	[[alternative HTML version deleted]]



More information about the R-help mailing list