1

I would like to add day axis labels at noon for each day of my chart. Currently, it adds the labels at midnight, but I'd prefer it if those labels were spaced midway between each day, while retaining grid lines denoting midnight. I tried using hjust but the results didn't look very good. Is there a way to do this?

library(ggplot2)
library(scales)

dat <- data.frame(time_value=seq(as.POSIXct("2011-07-01"), length.out=24*30, by = "hours"),
                  usage_value=sample(1:10, 24*30, replace=TRUE),
                  group=1)
dat$week <- format(dat$time_value, '%W')
dat <- subset(dat, week == 27)

ggplot(dat, aes(x=time_value, y=usage_value, group=1)) + 
  scale_x_datetime(breaks='day', labels=date_format('%A')) +
  geom_line()
Erik Shilts
  • 4,389
  • 2
  • 26
  • 51

1 Answers1

2

Here is one way.

First, create the noontime data. This is quite easy using seq.Date:

Then add a geom_vline to your plot:

noon <- data.frame(
  x=with(dat, seq(from=min(time_value), to=max(time_value), by="1 day"))+12*60*60
)

ggplot(dat, aes(x=time_value, y=usage_value, group=1)) + 
  geom_line() +
  geom_vline(data=noon, aes(xintercept=x), col="blue") 

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Thanks, though I'm looking for a way to shift the axis labels to where those noon lines are. – Erik Shilts Apr 25 '12 at 19:13
  • 2
    @ErikShilts Just pass the date sequence Andrie constructed to the breaks argument: `scale_x_datetime(breaks = noon$x,...)`. – joran Apr 26 '12 at 00:53
  • passing a dates sequence works if you are hardcoding it but my suggestion is to just subtract 12 hours from the data and let ggplot2 handle the labels – ideamotor Dec 29 '20 at 23:46