我如何在rbind之后和嵌套循环内绘制单个ggplot

问题描述

在此代码中,我想在循环中为每个alpha绘制ggplot,y轴分别使用ylim(min(Pro_df $ Relative_Error),max(Pro_df $ Relative_Error)),图中的每个alpha,这就是我想要的7 ggplot。另外,我希望在geom_Boxplot中单独为每个alpha提供图形。我试图通过下面的代码来做到这一点,但是没有用。

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)
  }

所有先前的代码都可以正常工作,现在我想绘制ggplot和Boxplot,因此在关闭一个循环之前,我编写了以下代码,但由于上面的问题而无法正常工作。

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)))
}

解决方法

对我来说,最终所需的输出是什么还不是很清楚,但是无论您是否缺少一种在创建循环时在循环中累积图的方法。在下面的代码片段中,我在循环开始之前实例化了一个列表,并在循环内部添加了每个图的列表。循环完成后,您现在可以浏览列表中的图,例如通过调用print(lst.plots$[["map2"]]$[["0.375"]])来查看最后一个箱线图。

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
}