0
votes

In this code I want to draw ggplot inside the loop for each alpha and y axis takes the ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)), each alpha in a graph individually, that's mean I want 7 ggplot. Also, I want geom_boxplot individually in a graph for each alpha. I tried to do that by the following code but it did not work.

library(ggplot2)
library(gganimate)

Pro_df <- data.frame(
  x = integer(0),
  Alpha = numeric(0), 
  Relative_Error = numeric(0))

mu=7      # Mean Value
sigma2=4   # Variance value

for (alpha in c(0.001,0.01,0.025,0.05,0.1,0.25,0.375))
{
  for (i in 1:13) 
  {
   
    E_PDF=dnorm(i,mean=mu,sd=sqrt(sigma2))
    
    Relative_Error=(5-E_PDF)/(1-E_PDF) 
    
    newrow <- data.frame(x = i, 
                         Alpha = alpha, 
                         Relative_Error = Relative_Error)
    
    Pro_df <- rbind(Pro_df, newrow)
  }

all the previous code work correctly, now I want to plot my ggplot and boxplot so before close the first loop I wrote the following code but it did not work as I want in my question above.

print(map2 <- ggplot() +
    geom_boxplot(data = Pro_df, 
                 aes( , y =Relative_Error),
                 colour = "red", size = .5))      

print(ggplot(Pro_df, aes(x =x, y =Relative_Error, colour = Alpha)) +
          geom_line() +
          ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)))
}
1

1 Answers

0
votes

It's not completely clear to me what your final desired output is, but regardless you are missing a way to accumulate the plots within your loop as they are created. In the below code snippet I have instantiated a list before the loops begin, and inside the loops I add each plot the list. Once the loops complete, you can now browse the plots inside the list, e.g. by calling print(lst.plots$[["map2"]]$[["0.375"]]) to see the last boxplot.

library(ggplot2)
library(gganimate)

Pro_df <- data.frame(
  x = integer(0),
  Alpha = numeric(0), 
  Relative_Error = numeric(0))

mu=7      # Mean Value
sigma2=4   # Variance value

lst.plots=list(map2 = list(),
               other = list())

for (alpha in c(0.001,0.01,0.025,0.05,0.1,0.25,0.375))
{
  for (i in 1:13) 
  {
    E_PDF=dnorm(i,mean=mu,sd=sqrt(sigma2))
    
    Relative_Error=(5-E_PDF)/(1-E_PDF) 
    
    newrow <- data.frame(x = i, 
                         Alpha = alpha, 
                         Relative_Error = Relative_Error)
    
    Pro_df <- rbind(Pro_df, newrow)
  }
  print(map2 <- ggplot() +
          geom_boxplot(data = Pro_df,
                       aes( , y =Relative_Error),
                       colour = "red", size = .5))
  
  print(other <- ggplot(Pro_df, aes(x =x, y =Relative_Error, colour = Alpha)) +
          geom_line() +
          ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)))
  
  lst.plots$map2[[as.character(alpha)]]=map2
  lst.plots$other[[as.character(alpha)]]=other
}