我想用我想要突出显示的特定点来注释轮廓图(这些点存储在不同的数据集中)。当我尝试时,我收到一个错误:
错误:美学必须是长度为1或与dataProblems相同的长度:z
然而,当我试图制作一个可重现的例子时,我得到了一个不同的错误:
eval(expr,envir,enclos)中的错误:找不到对象'z'
可重复示例的代码如下:
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))
答案 0 :(得分:3)
ggplot
调用中的aes传递给其余的geoms。所以错误告诉你它无法在内部找到z,并且它仍然认为z应该是初始调用的z。
有多种方法可以解决这个问题,我认为最简单的解决方法是分别为每个geom提供数据:
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。你还有colour cannot be mapped in two different geoms的问题,所以我用pch和fill修复了它。