Srizza
Srizza

Reputation: 115

Retain first and last break label when setting date_breaks in scale_x_datetime

Dummy data:

library(tidyverse)

    df<-tibble(datetime=seq(as.POSIXct("2019-10-01 12:00:00"),as.POSIXct("2020-10-01 12:00:00"), by="15 min"),value=rnorm(35137,22,sd=1)) %>% 
  mutate(period=case_when(
    datetime>="2019-10-01" & datetime<="2019-12-31" ~ "Oct 1-Dec 31, 2019",
    datetime>"2019-12-31" & datetime<="2020-03-31" ~ "Jan 1-Mar 31, 2020",
    datetime>"2020-03-31" & datetime<="2020-06-30" ~ "Apr 1-Jun 30, 2020",
    datetime>"2020-06-30" & datetime<="2020-10-01" ~ "July 1-Sept 30, 2020"),
    period=factor(period,levels = c("Oct 1-Dec 31, 2019","Jan 1-Mar 31, 2020","Apr 1-Jun 30, 2020","July 1-Sept 30, 2020")))


plots<- map(.x = unique(df$period), ~ df %>% 
                     dplyr::filter(period == .x) %>% 
                     ggplot()+
                     geom_point(aes(x=datetime,y=value),fill="blue")+
                     scale_x_datetime(date_labels = "%b-%d-%Y",
                                      date_breaks = "2 weeks",
                                      expand = c(0,0)))


plots[[1]]

I am making multiple plots and want to generalize the script to start and end the x axis labels with the first and last records from each group. I would like to have labels every 2 weeks starting Oct-01-2019. When I use I use date_breaks it drops the first and last labels and setting the limits is not working. I don't want to set the labels manually since each period will have different labels.

plots1

When I remove expand and date_breaks resulting in: scale_x_datetime(date_labels = "%b-%d-%Y")

This is what I get but it is by month not by every 2 weeks:

plots2

Upvotes: 3

Views: 552

Answers (1)

anilewe
anilewe

Reputation: 389

Then the workaround would be, based on the answer here, just increasing number of breaks to desired amount:

library(tidyverse)

    df<-tibble(datetime=seq(as.POSIXct("2019-10-01 12:00:00"),as.POSIXct("2020-10-01 12:00:00"), by="15 min"),value=rnorm(35137,22,sd=1)) %>% 
  mutate(period=case_when(
    datetime>="2019-10-01" & datetime<="2019-12-31" ~ "Oct 1-Dec 31, 2019",
    datetime>"2019-12-31" & datetime<="2020-03-31" ~ "Jan 1-Mar 31, 2020",
    datetime>"2020-03-31" & datetime<="2020-06-30" ~ "Apr 1-Jun 30, 2020",
    datetime>"2020-06-30" & datetime<="2020-10-01" ~ "July 1-Sept 30, 2020"),
    period=factor(period,levels = c("Oct 1-Dec 31, 2019","Jan 1-Mar 31, 2020","Apr 1-Jun 30, 2020","July 1-Sept 30, 2020")))


plots<- map(.x = unique(df$period), ~ df %>% 
                     dplyr::filter(period == .x) %>% 
                     ggplot()+
                     geom_point(aes(x=datetime,y=value),fill="blue")+
                     scale_x_datetime(date_labels = "%b-%d-%Y",
                                      breaks = scales::pretty_breaks(n = 10),
                                      expand = c(0.1,0)))


plots[[1]]

enter image description here

Upvotes: 1

Related Questions