如何告诉ggplot避免绘制丢失的日期

时间:2018-04-19 19:00:39

标签: r ggplot2

您好我有这样的数据:

> x
       value       Date
14 -2.224791 2000-01-31
15 -2.203189 2000-04-30
16 -2.216392 2000-07-31
17 -2.259517 2000-10-31
18 -2.252137 2001-01-31
19 -2.200599 2015-01-31
20 -2.229062 2015-04-30
21 -2.258825 2015-07-31
22 -2.288452 2015-10-31
> ggplot(x,aes(x=Date,y=value))+geom_line()

在尝试绘图时,ggplot正在推断缺失的日期,即2001年至2015年之间。我如何告诉ggplot不绘制不可用的值? enter image description here

1 个答案:

答案 0 :(得分:0)

library(tidyverse)

value = c(-2.224791, -2.203189, -2.216392, -2.259517, -2.252137, -2.200599, -2.229062, -2.258825, -2.288452)
date = as.Date(c("2000-01-31","2000-04-30","2000-07-31","2000-10-31","2001-01-31","2015-01-31","2015-04-30","2015-07-31","2015-10-31"))
data = data.frame(value,date)

data_2001 = data %>%
  filter(date <= "2001-12-31")

data_2015 = data %>%
  filter(date >= "2015-01-01")

plot = ggplot() +
  geom_line(data = data_2001
            , aes(x=date,y=value)) +
  geom_line(data = data_2015
            , aes(x=date,y=value))

print(plot)

enter image description here