针对我最近的一个问题,这个问题有点不同,使用更简单的例子更完整地解释了问题。以下是两组数据和三个函数。第一个函数绘制了一些点和一个预期的圆:
library("ggplot2")
library("grid")
td1 <- data.frame(x = rnorm(10), y = rnorm(10))
tf1 <- function(df) { # works as expected
p <- ggplot(aes(x = x, y = y), data = df)
p <- p + geom_point(color = "red")
p <- p + annotation_custom(circleGrob())
print(p)
}
tf1(td1)
下一个示例似乎要求精确的样本图,但代码略有不同。它不会报错,但不会绘制圆形:
tf2 <- function(df) { # circle isn't draw, but no error either
p <- ggplot()
p <- p + geom_point(data = df, aes(x = x, y = y), color = "red")
p <- p + annotation_custom(circleGrob())
print(p)
}
tf2(td1)
最后一个涉及到更复杂的审美,当你尝试创建圆形时会得到一个空的层。
td3 <- data.frame(r = c(rnorm(5, 5, 1.5), rnorm(5, 8, 2)),
f1 = c(rep("L", 5), rep("H", 5)), f2 = rep(c("A", "B"), 5))
tf3 <- function(df) {
p <- ggplot()
p <- p + geom_point(data = df,
aes(x = f1, y = r, color = f2, group = f2))
# p <- p + annotation_custom(circleGrob()) # comment out and it works
print(p)
}
tf3(td3)
现在,我怀疑这里的问题不是代码,而是我没有理解ggplot2的内部工作原理。 我确实需要一个解释,为什么在第二种情况下圆圈没有被绘制,以及为什么在第三种情况下层是空的。 我查看了annotation_custom
的代码,它有一个硬编码的inherit.aes = TRUE
,我认为这就是问题所在。我不明白为什么这个函数需要任何美学元素(请参见其文档)。我尝试了几种方法来覆盖它并设置inherit.aes = FALSE
,但我无法完全进入命名空间并使其生效。我试图检查ggplot2创建的对象,但这些proto
对象嵌套得非常深,很难解读。
annotation_custom
。 - stevecggplot2
版本。 - Bryan Hanson