叠加轮廓和线图

问题描述 投票:0回答:0

我想做出如下图.

我已经计算出路径,并将其存储在数据框中。

path <- matrix(0, nrow = 4, ncol = 20)
path[1, ] <- c(1:20) / 20
path[2, ] <- -c(1:20) / 20
path[3, ] <- c(1:20) / 30
path[4, ] <- -c(1:20) / 30
path <- as.data.frame(t(path))
colnames(path) <- c("x1", "x2", "p1", "p2")
path

我也有等值线图的值

normalDensity <- function(x1, x2) 
{
  total <- length(x1)
  result <- rep(0, total)
  for (i in 1:total)
  {
    result[i] <- t(c(x1[i], x2[i]) %*% sigmaInv %*% c(x1[i], x2[i]))
  }
  return(-result/2)
}
x1 <- seq(-5, 5, 0.1)
x2 <- seq(-5, 5, 0.1)
grid <- expand.grid(X1 = x1, X2 = x2)
grid <- mutate(grid, Z = normalDensity(grid$X1, grid$X2))

如何将路径添加到等高线图上?简单地使用 +

geom_path()
是行不通的。

我试过这个,但它不起作用。我也没有得到有用的错误

pathPlot <- ggplot(grid, aes(X1, X2, z = Z)) 
pathPlot <- pathPlot + geom_contour() + geom_contour_filled()
pathPlot <- pathPlot + geom_path(path, aes(x1, x2))

pathPlot 
r ggplot2 contour
© www.soinside.com 2019 - 2024. All rights reserved.