在列表中保存ggplot给了我相同的图表

时间:2017-09-26 03:40:14

标签: r ggplot2

我试图在3乘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")
}

使用曲线校正曲线:

plot

1 个答案:

答案 0 :(得分:2)

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

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

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)

workaround 1

解决方法2 。将所有数据放在数据框中,&amp;为每个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()

workaround 2