为什么ggplot2在添加文本注释时重复(unfacet)我的数据?

时间:2013-01-26 01:21:15

标签: r ggplot2

好吧,这让我很难过。我有这个功能:

tf <- function(formula = NULL, data = NULL) {
res <- as.character(formula[[2]])
fac2 <- as.character(formula[[3]][3])
fac1 <- as.character(formula[[3]][2])

# Aesthetic & Data 1
p <- ggplot(aes_string(x = fac1, y = res, color = fac1), data = data) +
    facet_grid(paste(".~", fac2)) + geom_point() # OK if we only go this far

facCounts <- count(data, vars = c(fac2, fac1))
facCounts$label <- paste("n = ", facCounts$freq , sep = "")
facCounts$y <- min(data$res) - 0.1*diff(range(data$res))
facCounts <- facCounts[,-3]
names(facCounts) <- c("f2", "f1", "lab", "y") # data frame looks correct

# Aesthetic & Data 2
p <- p + geom_text(aes(x = f1, y = y, label = lab),
        color = "black", size = 4.0, data = facCounts) + facet_grid(".~f2")
p
}

使用此数据运行时,请致电:

set.seed(1234)
mydf <- data.frame(
    resp = rnorm(40),
    cat1 = sample(LETTERS[1:3], 40, replace = TRUE),
    cat2 = sample(letters[1:2], 40, replace = TRUE))

p <- tf(formula = resp~cat1*cat2, data = mydf); print(p)

制作这张照片:

enter image description here

如果仔细观察,您会发现两个方面的数据实际上是相同的。对于显示的数据(并存储在facCounts中),计数是正确的。如果对geom_text的调用已被注释掉,则图表是正确的。 geom_text调用的各种更改都会让我看到您在上面看到的内容,或者存在正确的数据但计数文本重叠。我找不到这个迷宫的出路! + annotate("text", ...)的尝试也不起作用。保持数据分面和计数正确需要进行哪些更改?谢谢。这是ggplot 0.9.3 btw。

1 个答案:

答案 0 :(得分:2)

现在我确信自己会这样做:

tf <- function(formula = NULL, data = NULL) {
  res <- as.character(formula[[2]])
  fac2 <- as.character(formula[[3]][3])
  fac1 <- as.character(formula[[3]][2])

  # Aesthetic & Data 1
  p <- ggplot(aes_string(x = fac1, y = res, color = fac1), data = data) +
    facet_grid(paste(".~", fac2)) + geom_point() # OK if we only go this far

  facCounts <- count(data, vars = c(fac2, fac1))
  facCounts$label <- paste("n = ", facCounts$freq , sep = "")
  facCounts$y <- min(data$res) - 0.1*diff(range(data$res))
  facCounts <- facCounts[,-3]
  names(facCounts) <- c("cat2", "f1", "lab", "y") # data frame looks correct

  # Aesthetic & Data 2
  p <- p + geom_text(aes(x = f1, y = y, label = lab),
                     color = "black", size = 4.0, data = facCounts)
  p
}

您使用不同名称的分面变量第二次调用facet_grid。删除第二个调用并将f2重命名为`cat2似乎有效。