gpt4 book ai didi

r - 将 ggplot 保存在列表中给出了相同的图表

转载 作者:行者123 更新时间:2023-12-02 03:47:14 24 4
gpt4 key购买 nike

我正在尝试在 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")
}

使用曲线正确绘图:

plot

最佳答案

在循环中创建的 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)

workaround 1

解决方法 2。将所有数据放入一个数据框中,并为每个 ISI 创建一个带有构面的 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

关于r - 将 ggplot 保存在列表中给出了相同的图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46417470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com