cppiscute
cppiscute

Reputation: 747

Looping for ggplot how to use the for loop variable i inside the loop

I have a dataframe (what is the dataframe? i,e is not important). I am using that and plotting some point curves. like below

#EXP <- 3 (example)
#EXP_VEC <- c(1:EXP)

for (i in 1:EXP)
{
gg2_plot[i] <- ggplot(subset(gg2,Ei == EXP_VEC[i] ),aes(x=hours, y=variable, fill = Mi)) + geom_point(aes(fill = Mi,color = Mi),size = 3)
}

As you can see EXP_VEC = c(1,2,3.......) (Depends on user input Ex: if user inputs 2 then EXP_VEC = c(1,2))

Dataframe has Ei = 1,2,3,4,........

Now I have to do the plotting for all these Ei values depending on the user input.

Consider, EXP_VEC=3 now the for loop should produce three plots for Ei = 1 , Ei = 2 and Ei = 3 for this if the for loop I have written works then it would have been done and finished.

But obviously for loop is not working. I cant use aes_string because variable "i" is outside the aes().

Ex: consider the following dataset

dd<-data.frame(
    Ei = c(1L, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2), 
    Mi = c(1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2), 
    hours = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3), 
    variable = c(0.1023488, 0.1254325, 0.1523245, 0.1225425, 0.1452354, 
    0.1853324, 0.1452369, 0.1241241, 0.0542232, 0.8542154, 0.021542, 
    0.2541254))

As you can see I have two sets of Ei, I want to plot 1st plot for Ei = 1 and then beside this plot I want to again plot for Ei = 2.

So I thought of saving the plots for Ei=1 and Ei=2 in two separate variables and then using then in some kind of cascade function which I am yet to find out. How do I do it?

Is there a easy way to do this by just using ggplot without any loop? If not then how can I call "i" value inside my for loop?

Upvotes: 0

Views: 1115

Answers (1)

agstudy
agstudy

Reputation: 121608

I would do something like this:

plot_exp <- 
  function(i){
    dat <- subset(gg2,Ei == i )
    if (nrow(dat) > 0)
       ggplot(dat,aes(x=hours, y=variable, fill = Mi)) + 
              geom_point(aes(color = Mi),size = 3)
  }

ll <- lapply(seq_len(EXP), plot_exp)

ll is a list of plot of ggplot objects.

Upvotes: 2

Related Questions