我有一些类似于以下内容的数据:
library(dplyr)
library(ggplot2)
dates <- c('2023-01-01','2023-01-02','2023-01-03','2023-01-04','2023-01-05','2023-01-06',
'2023-01-07','2023-01-08','2023-01-09','2023-01-10','2023-01-11','2023-01-12',
'2023-01-01','2023-01-02','2023-01-03','2023-01-04','2023-01-05','2023-01-06',
'2023-01-07','2023-01-08','2023-01-09','2023-01-10','2023-01-11','2023-01-12',
'2023-01-01','2023-01-02','2023-01-03','2023-01-04','2023-01-05','2023-01-06',
'2023-01-07','2023-01-08','2023-01-09','2023-01-10','2023-01-11','2023-01-12')
values <- c(1,2,10,15,16,17,17,16,15,12,10,8,2,5,6,7,7,7,7,8,8,8,9,8,20,19,18,10,10,7,6,6,5,5,3,2)
grp1 <-rep('Group1',12)
grp2 <-rep('Group2',12)
grp3 <-rep('Group3',12)
groups <- c(grp1, grp2, grp3)
df <- cbind(dates, values, groups) |>
as.data.frame() |>
mutate(values = as.numeric(values),
dates = as.Date(dates))
我想绘制每组随时间变化的值。所以,我构建了以下 ggplot 代码:
ggplot(data = df, aes(x = dates, y = values, color = groups)) +
geom_line() +geom_point() +
facet_wrap(~ groups, scales = 'free_y', ncol = 1)
但是,我想添加每个面组都不同的垂直 x 截距线。这是我尝试满足此要求的一些额外代码:
cutoff_dates <- c('2023-01-02', '2023-01-04', '2023-01-06')
ggplot(data = df, aes(x = dates, y = values, color = groups)) +
geom_line() +geom_point() +
facet_wrap(~ groups, scales = 'free_y', ncol = 1) +
geom_vline(xintercept = as.Date(cutoff_dates), linetype = 'dashed')
但是,这会将每个截止值添加到每个分组图中。我希望第一个截止日期适用于第一组,第二个截止日期适用于第二组,依此类推。我应该如何修改我的代码才能达到这个结果?
谢谢!
您可以在不同的数据框中添加截止值,并将其映射为
aes()
内的美学geom_vline()
:
cutoff_dates <- data.frame(
cutoff = c('2023-01-02', '2023-01-04', '2023-01-06'),
groups = c("Group1", "Group2", "Group3"))
ggplot(data = df, aes(x = dates, y = values, color = groups)) +
geom_line() +
geom_point() +
facet_wrap(~ groups, scales = 'free_y', ncol = 1) +
geom_vline(data = cutoff_dates,
mapping = aes(xintercept = as.Date(cutoff)), linetype = 'dashed')