【问题标题】:How can I overlay points and lines onto a contour plot with ggplot2?如何使用 ggplot2 将点和线叠加到等高线图上?
【发布时间】:2015-09-08 23:07:37
【问题描述】:

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

错误:美学长度必须为 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))

【问题讨论】:

  • z 不在stuff 数据中,因此将inherit.aes=FALSE 添加到geom_point 调用以修复第一个错误。然后看看会发生什么

标签: r ggplot2 contour


【解决方案1】:

ggplot 将第一个 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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 2015-01-08
    • 2021-12-21
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多