1

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

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)

产生这张图片:

在此处输入图像描述

如果你仔细看,你会发现这两个方面的数据实际上是相同的。对于应该显示(并存储在 中)的数据,计数是正确的facCounts。如果调用 togeom_text被注释掉,那么情节是正确的。对呼叫的各种更改geom_text让我看到您在上面看到的内容,或者存在正确的数据但计数文本重叠。我找不到走出这个迷宫的路!尝试+ annotate("text", ...)也不起作用。需要进行哪些更改才能保持数据的多面性和正确的计数?谢谢。这是 ggplot 0.9.3 顺便说一句。

4

1 回答 1

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 似乎有效。

于 2013-01-26T02:05:06.613 回答