首页 > 解决方案 > 我如何在 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)))
}

标签: rfor-loopggplot2nested-loopsrbind

解决方案


我并不完全清楚你最终想要的输出是什么,但不管你是否错过了在创建循环时在循环中累积图的方法。在下面的代码片段中,我在循环开始之前实例化了一个列表,并在循环内添加了每个绘图列表。一旦循环完成,您现在可以浏览列表中的图,例如通过调用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
}

推荐阅读