Closed
Description
A custom breaks function on the date axis seem to mis-align the breaks and labels. Another does not. But corresponding date vector inputs for both functions work fine.
Not sure if this has already been reported - I've looked and found this issue, but it's old.
Reproducible example - note how the 30 March break shifts off the maximum data point it should align with.
require(tidyverse)
set.seed(pi)
df <- data.frame(date = Sys.Date() - 0:29, price = runif(30))
p <- ggplot(df, aes(date, price)) + geom_line() + geom_point() + coord_fixed(ratio=5)
# max price is 0.9101477 on 30 March
df %>% filter(price == max(price))
#> date price
#> 1 2020-03-30 0.9101477
weekend_breaks_correct <- function(x) {
mondays <- scales::fullseq(x, "1 week")
fridays <- mondays - lubridate::days(3)
sort(c(mondays, fridays))
}
weekend_breaks_misaligned <- function(x){
x <- seq(x[1], x[2], by=1)
x[weekdays(x) %in% c('Monday','Friday')]
}
( breaks_cor = weekend_breaks_correct(range(df$date)) )
#> [1] "2020-03-20" "2020-03-23" "2020-03-27" "2020-03-30" "2020-04-03"
#> [6] "2020-04-06" "2020-04-10" "2020-04-13" "2020-04-17" "2020-04-20"
#> [11] "2020-04-24" "2020-04-27"
( breaks_mis = weekend_breaks_misaligned(range(df$date)) )
#> [1] "2020-03-30" "2020-04-03" "2020-04-06" "2020-04-10" "2020-04-13"
#> [6] "2020-04-17" "2020-04-20" "2020-04-24"
# correct function
p + scale_x_date(date_labels = "%a %b %d", breaks = weekend_breaks_correct)
# misalisgned function
p + scale_x_date(date_labels = "%a %b %d", breaks = weekend_breaks_misaligned)
# vectors are both correct
p + scale_x_date(date_labels = "%a %b %d", breaks = breaks_cor)
p + scale_x_date(date_labels = "%a %b %d", breaks = breaks_mis)