我有一个包含以下值的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]))
答案 0 :(得分:2)
如下所示?
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]))