I am trying to create multiple scatter plot graphs in ggplot that have the same structure but with a different Y-value. I need them to be separate (and therefore not use facet_wrap) because in a later step I use grid_arrange to arrange different combinations of the graphs onto a single layout.
Because of this, I need to create new names for each plot that reflect the y-value being plotted. Below is sample code, where month is the variable on the x-axis and I want three separate plots of month vs. the three additional variables (lag1_var, lag3_var and lag9_var).
df <- data.frame (month= c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
lag1_var= c (10, 20, 30, 40, 10, 40, 30, 50, 70, 90, 100, 100),
lag3_var= c(90, 70, 50, 40, 70, 50, 20, 50, 70, 90, 10, 10),
lag9_var = c(50, 20,90, 100, 90, 10, 40, 90, 100, 20, 30, 70))
My approach was to create a list of the values that differ between the y-values and loop over that list like below:
loop.list <- c("1", "3", "9")
for (val in loop.list) {
yval<- paste0("lag", val, "_var")
ptitle <-paste0("graph plot lag", val, "_Var")
assign(paste0("plot", val), ggplot(data=df, aes(x=month, y=get(yval)))
+geom_point(color="red", size=2) + ggtitle(ptitle))
}
when I do this, I get three plots with three different names (plot1, plot3, plot9) and the correct titles (so plot 1 has the title "graph plot lag1" and plot 3 has the title "graph plot lag3", etc.), but they are all identical plots. So the loop is working for the plot name and for the plot title, but not for the y-value. It just outputs the values from the last loop (for the variable lag9_var).
I cannot figure out why this is happening, and why it only happens to the Y-value and not the title or plot name. I have always programmed in SAS and am new to R, so I think I am approaching this from a SAS prospective instead of thinking about it in the "R" way.
Note: in the code above I create the objects "yval" and "ptitle" outside of the ggplot statement, but only to help troubleshoot. the same thing happens if I include them in ggplot statement like below:
for (val in loop.list) {
assign(paste0("plot", val), ggplot(data=df,aes(x=month,y=get(paste0("lag", val, "_var")))) +
geom_point(color="red", size=2) +
ggtitle(paste0("graph plot lag", val, "_Var")))
}
Thank you for any help!