如何通过 ID 制作多线图并与事件叠加

how to make a multi line plot by ID and overlay with event

我有一个如下所示的数据集:

示例数据可以通过代码构建:

ID<-c("1","1","1","1","2","2","2","3","3","3","4","4","4","4")
Days<-c("-5","1","18","30","1","8","16","1","8","6","-6","1","7","15")
Event<-c("","","P","","","","N","","","C","","","P","N")
Test_1<-c("82","95","67","99","58","57","68","25","87","68","77","87","98","55")
Test_2<-c("66","85","96","35","27","69","55","27","39","24","55","99","89","58")

Sample.data <- data.frame(ID, Days, Event, Test_1, Test_2)

我想制作一个看起来像这样的情节,但不知道如何制作。在 excel 中制作示例图对我来说太复杂了。所以我手绘了一个来展示我想要实现的目标。对不起,丑陋的图表。任何人都可以帮助和指导我吗?谢谢

这可能是一个很好的起点。下次请不要在引号之间的变量中包含所有值。 R 中只有字符必须用引号引起来。我检查了您的数据并找到了一种方法来获得与您想要的相似的曲线。我不明白变量 Event 因为它有空值。但是使用长格式数据,您可以使用测试变量中的分值创建类似的图。这里的代码使用 tidyverse 包中的函数 ggplot2dplyrtidyr:

library(tidyverse)
#Data
ID<-c(1,1,1,1,2,2,2,3,3,3,4,4,4,4)
Days<-c(-5,1,18,30,1,8,16,1,8,6,-6,1,7,15)
Test_1<-c(82,95,67,99,58,57,68,25,87,68,77,87,98,55)
Test_2<-c(66,85,96,35,27,69,55,27,39,24,55,99,89,58)
Event<-c("","","P","","","","N","","","C","","","P","N")
#Dataframe
Sample.data <- data.frame(ID, Days, Event, Test_1, Test_2,stringsAsFactors = F)
#Reshape
Sample.data %>% pivot_longer(-c(1:3)) %>%
  mutate(Event=ifelse(Event=="",NA,Event)) %>%
  ggplot(aes(x=Days,y=value,group=name,color=name,label=Event))+
  geom_line()+
  geom_text(position = position_dodge(0.9),show.legend = F)+
  facet_wrap(.~ID)+
  theme_bw()
 

输出: