How to reduce lead/lagging space in x-axis in ggplot for dates

Viewed 123

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?

1 Answers

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

Related