rggplot2

move tick marks in a bit on ggplot with date on the x-axis


mod_h1_h3_probs_canada %>% bind_rows(h1_mod1_mod3_qc_probs) %>% 
    mutate(Election = ymd(Election, truncated = 2L)) %>% ggplot(., 
    aes(x = Election, y = estimate, col = Party, shape = Model, 
        group = Model)) + geom_point() + facet_wrap(~fct_relevel(Party, 
    "PC", "Liberal", "NDP", "Bloc"), nrow = 2, ncol = 2) + scale_color_manual(values = c("lightblue", 
    "darkred", "orange", "cyan")) + guides(col = "none") + geom_hline(yintercept = 0) + 
    labs(x = "Election", y = "Delta P of voting for Party") + 
    geom_smooth(method = "loess", aes(linetype = Model), se = F, 
        linewidth = 1) + scale_x_date(breaks = "10 years", date_labels = "%Y", 
    limits = c(ymd("1970-01-01"), ymd("2020-01-01")), expand = c(0, 
        0), guide = guide_axis(angle = 90)) + theme(axis.text.x = element_text(size = 12))

Created on 2025-05-26 with reprex v2.1.1

I am not happy with how the tick marks start right at the plot boundaries. How do I nudge them in a bit? enter image description here


Solution

  • You should change the value of the expand parameter in scale_x_date(). Setting it to c(0,0) pushes the tick marks to the edge of the plot. I would start by removing the expand parameter entirely and see if that meets your needs. Compare these two plots for a simple example.

    DF <- data.frame(year=c(1970,1980,1990), Value =c(1,2,3))
    
    ggplot(DF, aes(year, Value)) + geom_point() 
    
    ggplot(DF, aes(year, Value)) + geom_point() + 
      scale_x_continuous(expand=c(0,0))