【问题标题】:saving ggplot in a list gives me the same graph将ggplot保存在列表中给了我相同的图表
【发布时间】:2017-09-26 03:40:13
【问题描述】:

我正在尝试在 3 x 4 网格上绘制 12 个不同的图。但是,它只绘制最后一个 12 次。谁能帮我?我受够了。谢谢

library(ggplot2)
library(gridExtra)

pmax=0.85
K_min = 0.0017
T = seq(100,1200,by=100)  ## ISIs
lambda =1/T
p=list()


for(i in (1:length(lambda))){
p[[i]]<-ggplot(data.frame(x = c(0, 1)), aes(x = x)) +
stat_function(fun = function (x) (lambda[i]*(1-(1-pmax))/K_min)*(1-x)^((lambda[i]/K_min)-1)*
                                    (1-(1-pmax)*x)^-((lambda[i]/K_min)+1),colour = "dodgerblue3")+
scale_x_continuous(name = "Probability") +
scale_y_continuous(name = "Frequency") + theme_bw()
main <- grid.arrange(grobs=p,ncol=4)

}

此代码生成正确的图片,但我需要使用 ggplot,因为我的其他数字在 ggplot 中。

par( mfrow = c( 3, 4 ) )
for (i in (1:length(lambda))){

  f <- function (x) ((lambda[i]*(1-(1-pmax))/K_min)*(1-x)^((lambda[i]/K_min)-1)*
                  (1-(1-pmax)*x)^-((lambda[i]/K_min)+1) )
  curve(f,from=0, to=1, col = "violet",lwd=2,sub = paste0("ISI = ",round(1/lambda[i],3), ""),ylab="PDF",xlab="R")
}

使用曲线正确绘图:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    在循环中创建的 ggplot 对象在循环结束时进行评估。由于本例中的所有 ggplot 对象都使用使用 lambda[i] 计算的数据,因此它们根据最后一个 i 值 (12) 得到相同的结果。以下是两种可能的解决方法:

    解决方法 1。将每个 ggplot 对象转换为循环内的一个 grob,并将其保存到列表中:

    for(i in (1:length(lambda))){
      # code for generating each plot is unchanged
      g <- ggplot(data.frame(x = c(0, 1)), aes(x = x)) +
        stat_function(fun = function (x) (lambda[i]*(1-(1-pmax))/K_min)*(1-x)^((lambda[i]/K_min)-1)*
                        (1-(1-pmax)*x)^-((lambda[i]/K_min)+1),colour = "dodgerblue3")+
        scale_x_continuous(name = "Probability") +
        scale_y_continuous(name = "Frequency") + theme_bw()
    
      p[[i]] <- ggplotGrob(g)
    }
    
    main <- grid.arrange(grobs=p, ncol=4)
    

    解决方法 2。将所有数据放在一个数据框中,并为每个 ISI 创建一个带有 facet 的单个 ggplot:

    library(dplyr)
    
    pmax = 0.85
    K_min = 0.0017
    ISI = seq(100, 1200, by = 100)  # I changed this; using `T` as a name clashes with T from TRUE/FALSE
    lambda = 1/ISI
    
    df <- data.frame(
      x = rep(seq(0, 1, length.out = 101), length(ISI)),
      ISI = rep(ISI, each = 101),
      l = rep(lambda, each = 101)
    ) %>%
      mutate(y = (l * pmax / K_min) * (1-x) ^ ((l / K_min) - 1) *
               (1 - (1 - pmax) * x)^-((l / K_min) + 1))
    
    ggplot(data,
           aes(x = x, y = y, group = 1)) +
      geom_line(colour = "dodgerblue3") +
      facet_wrap(~ISI, nrow = 3, scales = "free_y") +
      labs(x = "Probability", y = "Frequency") +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      相关资源
      最近更新 更多