Search code examples
rdateggplot2axis

how to skip every other date label on x-axis in ggplot R


consider plot below ( data is from the useful link : How to create custom date labels using ggplot with scale_x_date )

start_date <- as.Date('2020-08-08')
end_date <- as.Date('2021-05-10')

# tibble with test data
df <- tibble( dates = as.Date(as.character(seq(start_date, end_date, by = 4) ) ), 
                 yval = as.numeric(strftime(dates, format = "%d")),
                 # following two lines just to give some color to the plot
                 month = strftime(dates, format = "%m") ) %>%
                 group_by( month ) 
df
  ggplot(df, aes( x=dates, y=yval, color = month ) ) +
  geom_point() +
  scale_x_date(date_labels = "%b %d", breaks = "1 month")

enter image description here

what I want is NOT to have the 2nd, the 4th , the 6th,... labels on the xaxis.
I tried "2 month" for breaks but it does the opposite and removes the 1st , 3d, 5th, ... labels.
any ideas how to do this ( preferably without manually specifying the labels one by one )


Solution

  • I tried to get this passing a function to breaks but that didn't work, so I made the sequence directly using start_date and end_date:

    ggplot(df, aes( x=dates, y=yval, color = month ) ) +
      geom_point() +
      scale_x_date(
        date_labels = "%b %d", 
        breaks = 
          seq(from = floor_date(start_date, "month"), to = end_date, by = "2 months"))
      )
    

    enter image description here