I have the following data frame:
ID <- c('1P', '1P', '1P', '2P', '2P', '2P', '3P', '3P', '3P')
Visit <- c('V1','V2','V3','V1','V2','V3','V1','V2','V3')
var1 <- c(100, 150, 125, 75, 90, 100, 50, 60, 110)
var2<-c(1.1, 0.8,0.7, 1, 0.5, 0.2, 1.8, 0.8, 0.3)
df<- data.frame(ID, Visit, var1, var2)
I've written a loop to plot a bar graph of var1 at each Visit for each ID.
df_split <- split(df, df$ID)
lapply(df_split, function(df) {ggplot(df, aes(x=Visit, y=var1)) +geom_col()})
I would like to:
- Draw a line on the same plots using the Visit on the x-axis and var2 on the y-axis and include a corresponding second y-axis on the right of each plot.
- Have the title of each graph be the corresponding ID
I have tried:
lapply(df_split, function(df) {ggplot(NULL) + geom_col(aes(x=Visit, y=var1)) + geom_line(aes(x=Visit, y=var2))})
But, this doesn't seem to work and the bar graphs all seem to plot the same data. I'm not at all sure how to add the title to the loop.
Many thanks for your time!