I have a plot with dates on X axis and I want to add shading to distinguish weekends and holidays. I figured I can do it using POSIXct. I define a function to figure out if a day is a weekend:
weekend<-function(data) {
d<-weekdays(data)
ifelse (d %in% c("niedziela","sobota", "Sunday", "Sun", "Saturday", "Sat"), "weekend", "working")
}
Then I define my datasets - the actual dataset ad a table of weekends:
dates=as.character(seq(as.Date("2018-10-24"), as.Date("2018-11-01"), "day"))
numbers=rnorm(length(dates))
tabela=data.table(dates=as.POSIXct(dates), numbers=numbers)
tabela[,day_type:=weekend(dates)]
tab_weekend<-tabela[day_type=='weekend']
tab_weekend[,Start:=dates-12*60*60+1]
tab_weekend[,Stop:=dates+12*60*60]
Then I plot the numbers as a line and the weekends as gray rectangles.
g<-ggplot(tabela)+
geom_line(aes(dates, numbers))+
geom_rect(data=tab_weekend, aes(xmin=Start, xmax=Stop, ymin=-Inf, ymax=+Inf),
fill='gray65', alpha=0.2)+
scale_x_datetime(labels=function(x) format(x, "%Y-%m-%d %H:%M"))
So far so good:
But if I now use a bigger range of dates,
dates=as.character(seq(as.Date("2018-10-01"), as.Date("2018-11-01"), "day"))
I get ticks every week which is not a problem in itself, but now the last tick shows the wrong date. Under the point of 29.10. (Monday) it says 28.10. 23:00.
I am guessing this happends because 28.10. is the first day of winter time, so it has 25 hours. But how do I fix it to have correct dates shown?
EDIT: it was suggested to use date_format with tz argument as in R: as.POSIXct timezone and scale_x_datetime issues in my dataset . However, with
scale_x_datetime(labels=date_format("%Y-%m-%d", tz = "Europe/Berlin"))
I still see ticks for 10-15, 10-22 and then 10-28.