按时间序列更改指定时间间隔的线型(实线到点线)

时间:2017-02-06 16:43:37

标签: r ggplot2

考虑以下示例:

library(ggplot2)
set.seed(30)

data <- data.frame(group = factor(1:11), 
                   year = c(rep(2014, times = 11), 
                            rep(2015, times = 11), 
                            rep(2016, times = 11), 
                            rep(2017, times = 11)), 
                   value = runif(44))

data$year <- as.Date(as.character(data$year), 
                     format = "%Y")

ggplot(data, aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  theme_bw()

enter image description here

我想在year == 2015点缀时右边的所有行,以及year == 2015时左边的所有行保持不变。怎么办呢?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

library(ggplot2)
set.seed(30)

data <- data.frame(group = factor(1:11), 
                   year = c(rep(2014, times = 11), 
                            rep(2015, times = 11), 
                            rep(2016, times = 11), 
                            rep(2017, times = 11)), 
                   value = runif(44))

data$int_year <- data$year
data$year <- as.Date(as.character(data$year), 
                     format = "%Y")

ggplot(subset(data, int_year <= 2015), aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  geom_line(data=subset(data, int_year >= 2015), aes(x = year, y = value, color = group), lty=2) + 
  theme_bw()

enter image description here

<强> [EDITED]

data1 <- subset(data, int_year <= 2015)
data2 <- subset(data, int_year >= 2015)
ggplot(data1, aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  geom_point(data=data2, aes(x = year, y = value, color = group)) + 
  geom_line(data=data2, aes(x = year, y = value, color = group), lty=2) + 
  theme_bw()

enter image description here