michellis
michellis

Reputation: 15

scale_x_date limits problem or filtering problem?

I'm trying to build a plot with geom_line based on the data from 1990 to 2020, and I'd like my x-axis breaks to be every 5 years. I've filtered the original data to the period 1990-2020, set the limits of scale_x_date and found other answers here on using expand = c(0,0), but there are still some extra years in the beginning that are messing with the breaks so the five years periods are not 1990-1995-2000 etc, but 1993-1998-2003 etc. The limits themselves work properly though, if you set any other dates. What might be the problem here? Thanks!!

Here's how the graph looks like

and here's my code:

library(tidyverse)
library(lubridate)
departures <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-27/departures.csv')
departures$fyear_gone <- lubridate::ymd(departures$fyear_gone, truncated = 2L)
by_year <- departures %>%  group_by(fyear_gone, ceo_dismissal) %>%
  filter(fyear_gone <= as.Date('2020-01-01') & fyear_gone >= as.Date('1990-01-01')) %>% 
  drop_na(ceo_dismissal) %>% count() %>% complete(ceo_dismissal=c(0,1), fill = list(n= 0L))
by_year$ceo_dismissal <- as.factor(by_year$ceo_dismissal)
ggplot(by_year, aes(fyear_gone, n, color=ceo_dismissal))+geom_line()+
  scale_x_date(date_labels="%y", breaks = "5 years", limits = as.Date(c("1990-01-01", "2020-01-01"), expand = c(0,0)))

Upvotes: 0

Views: 484

Answers (1)

r2evans
r2evans

Reputation: 160447

expand= is an argument to scale_x_date, but you have it within limits=as.Date(.), and it is being ignored:

as.Date("2020-02-01", expand=c(0, 0))
# [1] "2020-02-01"

Your limits should be one argument, then add one close-paren, then add expand=. Change from the first to the second:

scale_x_date(..., limits = as.Date(c("1990-01-01", "2020-01-01"), expand = c(0,0)))
scale_x_date(..., limits = as.Date(c("1990-01-01", "2020-01-01")), expand = c(0,0))

Ultimately,

... +
  scale_x_date(date_labels="%y", breaks = "5 years",
    limits = as.Date(c("1990-01-01", "2020-01-01")),
    expand = c(0,0)
  )

enter image description here

Upvotes: 1

Related Questions