gpt4 book ai didi

r - 使用 stat_function() 在 R 中的 ggplot 中绘制大量自定义函数

转载 作者:行者123 更新时间:2023-12-04 00:58:37 29 4
gpt4 key购买 nike

基本问题是我想弄清楚如何使用不同的函数系数值将大量(1000)自定义函数添加到 ggplot 中的同一个图形中。我已经看到其他关于如何添加两个或三个函数的问题,但不是 1000,以及关于添加不同的函数形式的问题,但不是具有多个参数值的相同形式......

目标是让 stat_function 使用存储在数据框中的参数值绘制线条,但没有 x 的实际数据。

[这里的总体目标是显示来自小数据集的非线性回归模型参数的巨大不确定性,这转化为与来自该数据的预测相关的不确定性(我试图说服其他人是一个坏主意)。我经常通过绘制由模型参数中的不确定性构建的许多线来做到这一点(a la Andrew Gelman's Multilevel Regression教科书)。]

例如,这是基本 R 图形中的绘图。

#The data
p.gap <- c(50,45,57,43,32,30,14,36,51)
p.ag <- c(43,24,52,46,28,17,7,18,29)
data <- as.data.frame(cbind(p.ag, p.gap))

#The model (using non-linear least squares regression):
fit.1.nls <- nls(formula=p.gap~beta1*p.ag^(beta2), start=list(beta1=5.065, beta2=0.6168))
summary(fit.1.nls)

#From the summary, I find the means and s.e's the two parameters, and develop their distributions:
beta1 <- rnorm(1000, 7.8945, 3.5689)
beta2 <- rnorm(1000, 0.4894, 0.1282)
coefs <- as.data.frame(cbind(beta1,beta2))

#This is the plot I want (using curve() and base R graphics):
plot(data$p.ag, data$p.gap, xlab="% agricultural land use",
ylab="% of riparian buffer gap", xlim=c(0,130), ylim=c(0,130), pch=20, type="n")
for (i in 1:1000){curve(coefs[i,1]*x^(coefs[i,2]), add=T, col="grey")}
curve(coef(fit.1.nls)[[1]]*x^(coef(fit.1.nls)[[2]]), add=T, col="red")
points(data$p.ag, data$p.gap, pch=20)

我可以用 ggplot 中的数据绘制平均模型函数:
fit.mean <- function(x){7.8945*x^(0.4894)}
ggplot(data, aes(x=p.ag, y=p.gap)) +
scale_x_continuous(limits=c(0,100), "% ag land use") +
scale_y_continuous(limits=c(0,100), "% riparian buffer gap") +
stat_function(fun=fit.mean, color="red") +
geom_point()

但是我没有在 ggplot 中绘制多条线。我似乎无法在 ggplot 网站或本网站上找到有关从函数中绘制参数值的任何帮助,这两者通常都非常有用。这是否违反了没有人敢这样做的阴谋论?

任何帮助表示赞赏。谢谢!

最佳答案

可以将多个几何图形或统计信息(甚至绘图的其他元素)收集到向量或列表中,并将该向量/列表添加到绘图中。使用这个,plyr包可用于制作 stat_function 的列表, 每行一个 coefs

library("plyr")
coeflines <-
alply(as.matrix(coefs), 1, function(coef) {
stat_function(fun=function(x){coef[1]*x^coef[2]}, colour="grey")
})

然后只需将其添加到情节中
ggplot(data, aes(x=p.ag, y=p.gap)) +
scale_x_continuous(limits=c(0,100), "% ag land use") +
scale_y_continuous(limits=c(0,100), "% riparian buffer gap") +
coeflines +
stat_function(fun=fit.mean, color="red") +
geom_point()

enter image description here

一些注意事项:
  • 这很慢。在我的电脑上画画花了几分钟。 ggplot在处理大约 1000 层时,它的设计效率并不高。
  • 这只是解决添加 1000 行的问题。根据@Roland 的评论,我不知道这是否代表您想要/期望的统计数据。
  • 关于r - 使用 stat_function() 在 R 中的 ggplot 中绘制大量自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846714/

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