3

I use scale_x_continuous to shrink the lead/lagging space on my ggplots. It works fine for numeric x-axis objects. However, have found no joy with dates.

My examples:

library(lubridate)  
library(tidyverse)

# this works
  ggplot(cars, aes(x = speed, y = dist)) +
  geom_line() +
  scale_x_continuous(expand = c(0, 0)) 


# this does not work
cars %>% 
  mutate(date = seq(dmy("01/01/2019"), dmy("01/01/2019") + ddays(nrow(cars) - 1), "day")) %>% 
  ggplot(aes(x = date, y = dist)) +
  geom_line() +
  scale_x_continuous(expand = c(0, 0))

Any ideas?

cephalopod
  • 1,826
  • 22
  • 31

1 Answers1

2

On your X-axis, you are dealing with date-type data and not with continuous data.

You may use the following code

cars %>% 
  mutate(date = seq(dmy("01/01/2019"), dmy("01/01/2019") + ddays(nrow(cars) - 1), "day")) %>% 
  ggplot(aes(x = date, y = dist)) +
  geom_line() +
  scale_x_date(expand = c(0, 0))

yielding the following plot

enter image description here

KoenV
  • 4,113
  • 2
  • 23
  • 38