Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign ggplot to a variable within for loop

Tags:

r

ggplot2

I am using this to print plots to a PDF within a for loop, which is working fine:

print(ggplot(subdata3, aes(x = Year, y = value, colour = Stat)) 
+ geom_line() + expand_limits(y=c(0,100)) 
+ ggtitle(paste0(as.character(ScenName),":\n", as.character(k))) 
+ ylab(paste0(j, " (", units, ")")))

Now, I need to assign each ggplot to a variable 'p', which will then be stored in a list and used by multiplot to arrange multiple plots on a page.

This is my attempt to assign the plot to a variable:

p <- ggplot(subdata3, aes(x = Year, y = value, colour = Stat)) 
+ geom_line() + expand_limits(y=c(0,100)) 
+ ggtitle(paste0(as.character(ScenName),":\n", as.character(k))) 
+ ylab(paste0(j, " (", units, ")"))

The only changes I made were to remove print() and make the variable assignment. After which, I receive this error:

Error in +ggtitle(paste0(as.character(ScenName), ":\n", as.character(k))) : 
  invalid argument to unary operator

I have tried many adjustments to the various sets of () in attempts find a solution, however, nothing seems to work.

Any thoughts?

like image 405
viridius Avatar asked Oct 19 '22 08:10

viridius


1 Answers

You've got your +s in the wrong place. Try this:

p <- ggplot(subdata3, aes(x = Year, y = value, colour = Stat)) +
  geom_line() + expand_limits(y=c(0,100)) +
  ggtitle(paste0(as.character(ScenName),":\n", as.character(k))) +
  ylab(paste0(j, " (", units, ")"))
like image 104
Edward R. Mazurek Avatar answered Nov 11 '22 15:11

Edward R. Mazurek