Mr.Spock
Mr.Spock

Reputation: 521

R - Loop with ggplot2, storing plots by column-names

I have a dataframe like this:

date_list = seq(ymd('2000-01-01'),ymd('2000-12-31'),by='day')
testframe = data.frame(Date = date_list)
testframe$ABC = rnorm(366)
testframe$DEF = rnorm(366)
testframe$GHI = seq(from = 10, to = 25, length.out = 366)
testframe$JKL = seq(from = 5, to = 45, length.out = 366)

I want to automatize the thing I am doing below. I want to plot each column from 2:4 against the time (Date). The plots should be saved in a form like p_columnname.

p_ABC = ggplot(data = testframe, aes(x = Date, y = ABC)) + 
  geom_line(color = "grey", size = 1) 

p_DEF = ggplot(data = testframe, aes(x = Date, y = DEF)) + 
  geom_line(color = "grey", size = 1) 

p_GHI = ggplot(data = testframe, aes(x = Date, y = GHI)) + 
  geom_line(color = "grey", size = 1) 

p_JKL = ggplot(data = testframe, aes(x = Date, y = JKL)) + 
  geom_line(color = "grey", size = 1) 

I tried to create a loop:

library(ggplot2)
theme_set(theme_gray()) 
for (i in colnames(testframe[2:ncol(testframe)])) {
  paste("p", i, sep = "_") = ggplot(data = testframe, aes(x = Date, y = i)) + 
    geom_line(color = "grey", size = 1) 
} 

That does not work! Any suggestions?

Upvotes: 0

Views: 214

Answers (2)

Varn K
Varn K

Reputation: 400

It may not be the best way to do it, but you can try with recursion.

f <- colnames(testframe)
sotc <- function(x){
if(is.na(f[x])){return()} 
else
{ assign(paste0("p_",f[x]),  
 ggplot(testframe,aes_string(f[1],f[x]))+geom_line(),envir = globalenv())}

 sotc(x+1)
  }

 sotc(2)

 p_ABC

Upvotes: 0

bouncyball
bouncyball

Reputation: 10771

Using a combination of lapply and aes_string, we can generate a list of plots. You can then extract each component of the list by name if necessary.

plot_list <- lapply(names(testframe)[-1], 
                    FUN = function(n) 
                        ggplot(testframe, aes_string("Date", n))+geom_line())

names(plot_list) <- paste0("p_", names(testframe)[-1])

plot_list$p_ABC

If you want to stick with the for loop framework, we can use the assign function:

for(n in names(testframe)[-1]){
  assign(paste0("p_", n),
         ggplot(testframe, aes_string("Date", n))+
           geom_line())
}

Upvotes: 1

Related Questions