使用日期扩展x轴

时间:2018-03-14 01:07:11

标签: r ggplot2

我希望使用ggrepel将标签添加到ggplot的行的末尾。为此,我需要为标签腾出空间。为此,我使用scale_x_continuous ot扩展x轴。不确定这是否正确,并且对其他策略持开放态度。

当x_axis类型为友好数字时,我可以这样做。

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") 

然而,当我尝试类似的东西,除了x轴是邪恶的日期类型,我得到错误:

  

as.Date.numeric(value)出错:&#39; origin&#39;必须提供

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) 

如何使用我的主要克星,日期?

2 个答案:

答案 0 :(得分:0)

使用scale_x_date代替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

答案 1 :(得分:0)

请注意,scale_x_date()有一个expand参数,可以精确控制x轴的开始和结束位置。您可以尝试使用expand = c(0,0)来仅包含limits = argument中指定的日期或expand = c(f,f)其中f是相对于您应该包含在整个时间序列记录中的天数的分数超出通过limit =参数指定的日期范围的图。例如,f可以是0.01。