Axis breaks at noon each day of ggplot2 chart

2019-08-07 07:40发布

问题:

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()

回答1:

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") 



标签: r ggplot2