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

痴心易碎 提交于 2019-12-10 23:27:16

问题


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.



来源:https://stackoverflow.com/questions/32468576/how-can-i-overlay-points-and-lines-onto-a-contour-plot-with-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!