考虑以下示例:
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()
我想在year == 2015
点缀时右边的所有行,以及year == 2015
时左边的所有行保持不变。怎么办呢?
答案 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()
<强> [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()