【问题标题】:How I draw individual ggplot after rbind and inside the nested loop我如何在 rbind 之后和嵌套循环内绘制单个 ggplot
【发布时间】:2021-01-24 19:44:04
【问题描述】:

在这段代码中,我想在循环内为每个 alpha 绘制 ggplot,y 轴采用 ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)),图中的每个 alpha 单独,这意味着我想要7 格图。另外,我希望 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)))
}

【问题讨论】:

    标签: r for-loop ggplot2 nested-loops rbind


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 2021-08-06
      • 2014-09-01
      相关资源
      最近更新 更多