我运行示例代码以生成描述马尔可夫链蒙特卡罗的图形。 https://github.com/davharris/mcmc-tutorial 但是,我遇到了最后一行代码抛出的以下异常。 “错误:美学必须是长度1或与数据相同(250000):x,y”
代码已在下面列出。
library(MASS)
library(ggplot2)
lik = function(x, y) {
dnorm(x - 3) * dnorm(y - x + 2)
}
grid.values = seq(min.x, max.x, length = 500)
grid = expand.grid(x = grid.values, y = grid.values)
z = lik(grid$x, grid$y)
gaussian.plot = ggplot(data = grid, aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_fill_gradient2() + coord_equal()
gaussian.plot
maxit = 50
samples = matrix(NA, nrow = maxit, ncol = 2, dimnames = list(NULL, c("x", "y")))
samples[1, ] = c(0, 0) # start at 0,0
for (i in 2:maxit) {
# propose a new sample point
proposal = samples[i - 1, ] + rnorm(2, mean = 0, sd = 1)
# Compare its likelihood with the current position
old.lik = lik(samples[i - 1, "x"], samples[i - 1, "y"])
new.lik = lik(proposal["x"], proposal["y"])
ratio = new.lik/old.lik
# flip a coin and accept the new proposal with probability min(ratio, 1)
if (rbinom(1, size = 1, prob = min(ratio, 1))) {
samples[i, ] = proposal
} else {
# If you don't accept the proposal, just keep what you had in the last
# time step
samples[i, ] = samples[i - 1, ]
}
}
gaussian.plot + geom_path(mapping = aes(x = samples[, "x"], y = samples[, "y"]),
color = "orange") + geom_point(mapping = aes(x = samples[, "x"], y = samples[,
"y"]))
答案 0 :(得分:0)
samples
是一个矩阵,将其转换为as.data.frame()
的数据框,以便ggplot2
可以使用它。
由于您希望的点数来自与用于顶部绘图的gaussian.plot
不同的数据帧,因此您需要定义数据的来源。
这应该有效:
gaussian.plot + geom_path(data=samples,aes(x = x, y = y),color = "orange") + geom_point(data=samples,aes(x = x, y = y))