gpt4 book ai didi

r - R 中的标记似然等高线图

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

我有一个包含以下值的 csv 文件。

x,y
50.0,0.0
50.0,0.0
51.0,0.0
53.0,0.0
54.0,0.0
54.0,0.0
54.0,0.0
55.0,0.0
55.0,0.0
56.0,0.0
56.0,0.0
57.0,0.0
57.0,0.0
57.0,1.0
57.0,1.0
58.0,0.0
59.0,0.0
60.0,0.0
60.0,1.0
61.0,0.0
61.0,0.0
61.0,1.0
61.0,1.0
62.0,1.0
62.0,1.0
62.0,0.0
62.0,1.0
63.0,0.0
63.0,0.0
63.0,1.0
64.0,0.0
64.0,1.0
65.0,0.0
67.0,1.0
67.0,1.0
68.0,0.0
68.0,1.0
69.0,0.0
70.0,1.0
71.0,0.0

我可以使用 contour() 函数和下面的代码在 R 中制作一个漂亮的等高线图,但我想使用 ggplot 制作同样的东西。有人可以展示如何做到这一点吗?我还在底部附上了一张图像,显示了当前代码的图形外观。 Likelihood Contour Image

#Read in the file `xy`
x<- xy$x
y<- xy$y
#Center age
x0 <- x-mean(x)
#fit glm
xglm <- glm(y~x0,family=binomial)
# 2d likelihood
b<- summary(xglm)$coef
#intercept estimate and se
b0hat<-xglm$coef[1]; se0<- b[1,2]
#slope estimate and se
b1hat<-xglm$coef[2]; se1<- b[2,2]
#Compute the log-likelihood
fun1 <- function(bo,b1){
sum(y*(bo+b1*x0)- log(1+exp(bo+b1*x0)))
}

lik<- NULL
#get range of values within +- 3 se for intercept
bbo<- seq(b0hat-3*se0, b0hat+3*se0 ,len=20)
#get range of values within +- 3 se for slope
bb1 <- seq(b1hat-3*se1, b1hat+3*se1,len=20)
for (bo in bbo)
{
for (b1 in bb1){
lik <- c(lik,fun1(bo,b1))
}
}
#get max likelihood
maxlik <- max(lik)
#get difference
lik <- lik-maxlik
#take the exponential of the likelihood
lik<- exp(lik)

contour(bbo,bb1,matrix(lik,20,byrow=T),level=seq(.1,1,by=.2),
xlab=expression(beta[0]),
ylab=expression(beta[1]))

最佳答案

类似于下面的内容?

library(ggplot2)
df.lik <- setNames(expand.grid(bbo, bb1), c('x', 'y'))
vfun1 <- Vectorize(fun1, SIMPLIFY = TRUE)

df.lik$z <- vfun1(df.lik$x,df.lik$y)
p <- ggplot(df.lik, aes(x, y, z=z)) + stat_contour(aes(colour = ..level..))
data<- ggplot_build(p)$data[[1]]
indices <- setdiff(1:nrow(data), which(duplicated(data$level))) # distinct levels
p +
geom_text(aes(label=seq(0,1,by=.1), z=NULL), data=data[indices,]) +
xlab(expression(beta[0])) +
ylab(expression(beta[1]))

enter image description here

关于r - R 中的标记似然等高线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688657/

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