I am creating multiple plots in a loop and then using marrangegrob to display in the grid. When I access the plot from a list example plotlist[[1]] it changes the Y axis. In my actual code I am returning the list of plots from a function and then using marrangegrob.
I tried the following code
data1 <- data.frame(SUBJID = c('a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'),
y1 = c(0, NA, 0, 1500, 700, 300, 450, 20000, 5000, 300),
NomTime = c(0, 4, 7, 14, 21, 0, 4, 7, 16, 22))
data2 <- data.frame(SUBJID = c('a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'),
y2 = c(0, 20, -100, -100, -90, 50, 0, 1000, -50, -80),
NomTime = c(-8, 0, 1, 7, 14, -6, 0, 1, 4, 7))
Sub = unique(intersect(data1$SUBJID, data2$SUBJID))
n = length(Sub)
plotlist = list()
for(i in Sub){
d1 = data1 %>%
filter(SUBJID == i)
d2 = data2 %>%
filter(SUBJID == i)
ratio <- max(d2$y2, na.rm=TRUE) / max(d1$y1, na.rm=TRUE)
title = unique(d1[c("SUBJID")])$SUBJID
if(ratio == 0){
break
}
p = ggplot(data=d1, aes(x=NomTime, y=y1))+
geom_line(data=d1, aes(y=y1, group=SUBJID), size=1, color = "blue") +
geom_line(data=d2, aes(y=y2/ratio, group=SUBJID), size=1, color = "orange") +
geom_point(data=d2, aes(y=y2/ratio), show.legend = FALSE)+
labs(x="Time (day)", y="First Y axis")+
ggtitle(paste0("SUBJID ", title)) +
scale_y_continuous(sec.axis = sec_axis(~.*ratio, name = "Second Y axis"))+
theme_bw()+
theme(plot.title=element_text(size = 10, face="bold"))+
theme(axis.title.y = element_text(size = 12, angle = 90, face="bold"))+
theme(axis.title.y = element_blank())+
theme(axis.text.y = element_text(size = 13))+
theme(axis.title.x = element_blank())+
theme(axis.title.x = element_text(size = 12, angle = 00, face="bold"))+
theme(axis.text.x = element_text(size = 12))+
theme(axis.title.x = element_blank())+
theme(plot.caption = element_text(colour="black", size=10, hjust = 0))+
theme(strip.text.x = element_text(size = 10, colour = "black"))+
theme(axis.title.y = element_text(color = CVCcolor, size=15),
axis.title.y.right = element_text(color = sBCMA, size=15))
plotlist[[i]] = p
print(p)
}
plotlist[[1]]
marrangeGrob(plotlist, nrow = 1, ncol = 2)