如何在图中添加线条和阴影

时间:2020-09-21 18:41:23

标签: r ggplot2

我有一个数据集,想为其作图。我的数据和绘图代码为:

#Data
Days<-c("-6","-6","-6","-1","-1","-1","1","6","6","6","13","13","13","16","20","20","20","24","28","28","28","44","44","44")
Event<-c("","","","","","","H","","","","","","","P","","","","H","","","","","","")
Dummy<-c("","","","","","","1","","","","","","","1","","","","1","","","","","","")
Item <-c("DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP")
Result <- c("100","68","149","98","80","142","","98","88","142","110","72","160","","102","69","159","","99","82","136","97","84","144")
#Dataframe
Sample.data <- data.frame( Days, Event,Dummy, Item, Result,stringsAsFactors = F) 
Sample.data %>% mutate(ID=1) %>% mutate (Name="Jack")

#Plot
ggplot(type.convert(Sample.data)) + 
  geom_line(aes(Days, Result, group = Item, color = Item))+ 
  geom_hline(yintercept=120)+
  geom_hline(yintercept=80)+
  geom_point(aes(x = Days, y =Dummy ))+
  geom_text(aes(x = Days, y =Dummy,label=Event,Vjust = 1.75))

我得到的情节是: enter image description here 我想进一步改善它,但不知道如何。有人可以帮忙吗?

  1. 我想在标记事件的地方添加垂直虚线;
  2. 我想对线之间的区域(y = 120和Y = 80)进行着色;
  3. 我不想在Item ==“”时绘制线条(没有任何线条,但是确实在图例中显示;
  4. 我想将“名称”添加到脚注或标题中。请注意,我要使用Sample.data $ Name而不是“ Jack”,因为我要进行1人以上的绘图,并且我将使用循环代码生成绘图,因此Name需要自行自动更改。

它看起来像这样:

enter image description here

对丑陋的情节感到抱歉。这是我可以通过绘画获得的最好的结果。 :(

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

library(ggplot2)
#Data
Days<-c("-6","-6","-6","-1","-1","-1","1","6","6","6","13","13","13","16","20","20","20","24","28","28","28","44","44","44")
Event<-c("","","","","","","H","","","","","","","P","","","","H","","","","","","")
Dummy<-c("","","","","","","1","","","","","","","1","","","","1","","","","","","")
Item <-c("DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","","DIABP","PULSE","SYSBP","DIABP","PULSE","SYSBP")
Result <- c("100","68","149","98","80","142","","98","88","142","110","72","160","","102","69","159","","99","82","136","97","84","144")
#Dataframe
Sample.data <- data.frame( Days, Event,Dummy, Item, Result,stringsAsFactors = F) 
Sample.data %>% mutate(ID=1) %>% mutate (Name="Jack")
#Create flags
Sample.data$Flag <- ifelse(Sample.data$Dummy==1,Sample.data$Days,NA)
#Plot
ggplot(type.convert(Sample.data)) + 
  geom_line(aes(Days, Result, group = Item, color = Item))+ 
  geom_ribbon(aes(x=Days,ymin=80,ymax=120),fill='blue',alpha=0.2)+
  geom_hline(yintercept=120)+
  geom_hline(yintercept=80)+
  geom_point(aes(x = Days, y =Dummy ))+
  geom_text(aes(x = Days, y =Dummy,label=Event,Vjust = 1.75))+
  geom_vline(aes(xintercept=Flag),lty='dashed')+
  scale_color_discrete(breaks=unique(Sample.data$Item[Sample.data$Item!='']))+
  labs(title='Jack',caption = 'Jack')

输出:

enter image description here