How can I overlay points and lines onto a contour

2019-07-08 19:19发布

问题:

I want to annotate a contour plot with particular points that I want to highlight (where these points are stored in a different data set). When I try, I get an error:

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

However, when I tried to make a reproducible example, I get a different error:

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

The code for the reproducible example is below:

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))

回答1:

ggplot passes the aes from the first ggplot call to the rest of the geoms, unless told otherwise. So the error is telling you that it cannot find z inside stuff, and it still thinks that the z should be z from the initial call.

There are a range of ways to fix this, I think the easiest way to fix it is to give each geom its data separately:

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)

NB. you also have a problem where colour cannot be mapped in two different geoms, so I've fixed it using pch and fill.