36.5 对数似然

set.seed(1234)
n <- 20 # 随机数的个数
x <- rexp(n, rate = 5) # 服从指数分布的随机数
m <- 40 # 网格数
mu <- seq(mean(x) - 1.5 * sd(x) / sqrt(n),
          mean(x) + 1.5 * sd(x) / sqrt(n),
          length.out = m
)
sigma <- seq(0.8 * sd(x), 1.5 * sd(x), length.out = m)
tmp <- expand.grid(x = mu, y = sigma)
loglikelihood <- function(b) -sum(dnorm(x, b[1], b[2], log = TRUE))
pp <- apply(tmp, 1, loglikelihood)
z <- matrix(pp, m, m)
nbcol <- 100
color <- hcl.colors(nbcol)
zfacet <- z[-1, -1] + z[-1, -m] + z[-m, -1] + z[-m, -m]
facetcol <- cut(zfacet, nbcol)

par(mar = c(0.1, 2, 0.1, 0.1))
persp(mu, sigma, z,
      xlab = "\n \u03bc", ylab = "\n \u03c3",
      zlab = "\n log-likelihood",
      border = NA,
      ticktype = "simple",
      col = color[facetcol],
      theta = 50, phi = 25,
      r = 60, d = 0.1, expand = .6,
      ltheta = 90, lphi = 180,
      shade = 0.1, nticks = 5, 
      box = TRUE, axes = TRUE
)