如何使用 ggplot2 将点和线叠加到等高线图上?

How can I overlay points and lines onto a contour plot with ggplot2?

我想用我想突出显示的特定点(这些点存储在不同的数据集中)来注释等高线图。当我尝试时,出现错误:

Error: Aesthetics must either be length one, or the same length as the dataProblems:z

然而,当我试图制作一个可重现的例子时,我得到了一个不同的错误:

Error in eval(expr, envir, enclos) : object 'z' not found

可重现示例的代码如下:

library(mnormt)
library(dplyr)
library(ggplot2)

f <- function(x, y) {
    dmnorm(x = c(x, y),
            mean = c(0, 0),
            varcov = diag(2))
}
f <- Vectorize(f)


xmesh <- seq(from = -3, to = 3, length.out = 100)
ymesh <- seq(from = -3, to = 3, length.out = 100)
dummy <- expand.grid(x = xmesh, y = ymesh)
dummy$z <- f(dummy$x, dummy$y)

stuff <- data_frame(x = c(0, 0, 1),
                    y = c(0, -1, -1),
                    point = c("O", "P", "Q"))

dummy %>%
    ggplot(aes(x = x, y = y, z = z)) +
    stat_contour(aes(color = ..level..)) +
    labs(color = "density") + 
    geom_point(data = stuff, mapping = aes(x = x, y = y, color = point))

ggplot 将来自第一个 ggplot 调用的 aes 传递给其余的 geom,除非另有说明。所以错误是告诉你它找不到 z inside stuff,它仍然认为 z 应该是初始调用中的 z。

有多种方法可以解决这个问题,我认为最简单的解决方法是分别为每个几何对象提供数据:

ggplot() +
  stat_contour(data = dummy, aes(x = x, y = y, z = z, color = ..level..)) +
  labs(color = "density") + 
  geom_point(data = stuff, aes(x = x, y = y, fill = factor(point)), pch = 21)

注意。你也有一个问题 colour cannot be mapped in two different geoms,所以我用 pch 和 fill 修复了它。