'Extend x-axis with dates

I wish to use ggrepel to add labels to the ends of the lines of a ggplot. To do that, I need to make space for the labels. To do that, I use scale_x_continuous ot extend the x-axis. Not sure that's correct and am open to other strategies.

I can do it when the x_axis type is friendly numeric.

library("tidyverse")
library("ggrepel")

p <- tibble (
  x = c(1991, 1999),
  y = c(3, 5)
)

ggplot(p, aes(x, y)) + geom_line()  + scale_x_continuous(limits = c(1991, 2020)) +
  geom_text_repel(data = p[2,], aes(label = "Minimum Wage"),  size = 4, nudge_x = 1, nudge_y = 0, colour = "gray50") 

However, when I try something similar except the x-axis is of the evil date type, I get the error:

Error in as.Date.numeric(value) : 'origin' must be supplied

p <- tibble (
  x = c(as.Date("1991-01-01"), as.Date("1999-01-01")),
  y = c(2, 5)
)
range <-  c(as.Date("1991-01-01"), as.Date("2020-01-01"))
ggplot(p, aes(x, y)) + geom_line() + scale_x_continuous(limits = range) 

How can I get this to work with my arch nemesis, date?



Solution 1:[1]

Use scale_x_date instead of scale_x_continuous:

p <- tibble (
  x = c(as.Date("1991-01-01"), as.Date("1999-01-01")),
  y = c(2, 5)
)
range <-  c(as.Date("1991-01-01"), as.Date("2020-01-01"))

ggplot(p, aes(x, y)) + geom_line() + scale_x_date(limits = range) 

enter image description here

Solution 2:[2]

Note that scale_x_date() has an expand argument which allows exact control over where the x-axis starts and ends. You could try expand = c(0,0) to include only the dates specified in your limits = argument or expand = c(f, f) where f is the fraction of days relative to the entire time series record you should include in your plot beyond the range of dates specified via your limit = argument. For example, f could be 0.01.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maurits Evers
Solution 2 ah bon