在对最近的mine问题进行跟进后,此问题有所不同,并使用更简单的示例更全面地说明了该问题。以下是两个数据集和三个功能。第一个按预期绘制了一些点和一个圆:

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,但是我无法完全穿透 namespace 并使它保持不变。我试图以ggplot2创建的对象为例,但是这些proto对象嵌套得非常深,难以破解。

最佳答案

要回答这个问题:



实际上annotation_custom需要x和y aes来缩放其grob,并在native单位之后使用。
基本上是这样做的:

  x_rng <- range(df$x, na.rm = TRUE)                            ## ranges of x :aes x
  y_rng <- range(df$y, na.rm = TRUE)                            ## ranges of y :aes y
  vp <- viewport(x = mean(x_rng), y = mean(y_rng),              ##  create a viewport
                 width = diff(x_rng), height = diff(y_rng),
                 just = c("center","center"))
  dd <- editGrob(grod =circleGrob(), vp = vp)                  ##plot the grob in this vp

为了说明这一点,我在虚拟绘图中添加了一个grob,用作我的grob的比例。第一个是大规模,第二个是小规模。
base.big   <- ggplot(aes(x = x1, y = y1), data = data.frame(x1=1:100,y1=1:100))
base.small <- ggplot(aes(x = x1, y = y1), data = data.frame(x1=1:20,y1=1:1))

我定义了我的grob,请参阅我将原始比例用于xmin,xmax,ymin,ymax
annot <- annotation_custom(grob = circleGrob(),  xmin = 0,
                                                 xmax = 20,
                                                 ymin = 0,
                                                 ymax = 1)

现在查看(base.big +annot)和(base.small + annot)之间的音阶差异(小点/大圆圈)。
library(gridExtra)
grid.arrange(base.big+annot,
             base.small+annot)

关于r - ggplot2 0.9.3中美学的继承和注记的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14415073/

10-09 10:16