user4250598
user4250598

Reputation:

Adding a vertical line by using a flag in the data frame

I have a data frame as follows:

df<-
 FORM  TIME   CONC  
  0     1      5
  0     2      10 
  0     5      11
  1     6      14
  1     7      15

I am plotting TIME versus CONC. I would like to add a vertical line at the TIME when the formulation changes from FORM 1 to FORM 2. I want to make my code for plotting so it can detect when the formulation changes automatically.

How should I write it in the ggplot line below:

plotobj <- plotobj + vline(aes(slope = 1, intercept = ??), linetype = "dashed", size = 1)

Upvotes: 0

Views: 160

Answers (1)

Pewi
Pewi

Reputation: 1134

If I read you correctly, this should help out:

library(ggplot2)

df = data.frame(FORM=c(0,0,0,1,1),TIME=c(1,2,5,6,7),CONC=c(5,10,11,14,15))

ggplot()+
   geom_line(data=df,aes(x=TIME,y=CONC))+
   geom_vline(xintercept = min(df$TIME[grep(1,df$FORM)]), linetype = "dashed", size = 1)

What is actually important:

min(df$TIME[grep(1,df$FORM)])

grep gives indexes for all FORM values equal to 1. We extract these and chose the one from the row with the smallest value of TIME using min. Finally using this index we pick the correponding value from df$TIME.

Upvotes: 1

Related Questions