Is it possible to use R to add the date onto a ggplot graph (upon which the graph data is based)? I have code which selects the most daily data over a the course of a week, and this subsequently gets plotted. An example dataframe (from a previous answer) is shown below:
set.seed(1234)
df <- data.frame(Date=seq(as.POSIXct("05:00", format="%H:%M"),
as.POSIXct("23:00", format="%H:%M"), by="hours"))
df$Counts <- sample(19)
df <- df[-c(4,7,17,18),]
# generate the groups automatically and plot
idx <- c(1, diff(df$Date))
i2 <- c(1,which(idx != 1), nrow(df)+1)
df$grp <- rep(1:length(diff(i2)), diff(i2))
g <- ggplot(df, aes(x=Date, y=Counts)) + geom_line(aes(group = grp)) +
geom_point()
g
I know I can use the following code to get R to work out which day of the week my data is:
d <- as.Date("19/02/2013","%d/%m/%Y")
format(d, "%A, %b %d, %Y")
But I obviously have to manually input the date for this to work.
Is it possible to get R to read the dataframe and work out the day of the week the data is based on (it will be only one day), and then add this as a legend in the top right hand corner of the graph? Ideally the format would include both the day and date (e.g. Tuesday, Feb 19th 2013).
Edit
I want to add the date as text in the graph. Can I use geom_text for this? This isn't working at the moment, but so far I have got:
g + geom_text(aes(x=as.POSIXct("18:00:00", format="%H:%M:%S"), y=1500), label=date_format("%A, %b %d, %Y")", size=2)
Can anyone advise me what I am doing wrong?