3

一些测试数据:

ltd <- data.frame(r = c(rnorm(10), f1 = c(rep("L", 5), rep("H", 5)),
       f2 = rep(c("A", "B"), 5))

还有一个最小的功能:

tf <- function(formula = NULL, data = NULL) {

res <- as.character(formula[[2]]) # clean & prep data
fac1 <- as.character(formula[[3]][2])
fac2 <- as.character(formula[[3]][3])

counts <- count(data, vars = c(fac2, fac1)) # get table data ready
colnames(counts) <- c(fac2, fac1, "count")
myt <- tableGrob(counts, show.box = TRUE,
    show.rownames = FALSE, show.colnames = TRUE,
    show.csep = TRUE, show.rsep = TRUE,
    separator = "black")

p <- ggplot()
p <- p + geom_point(data = data, 
    aes_string(x = fac1, y = res, color = fac2, group = fac2))      
p <- p + annotation_custom(myt) # comment out and it works
}

运行:

require("plyr")
require("gridExtra")
require("ggplot2")
tmp <- tf(formula = r~f1*f2, data = ltd)
print(tmp)

Error in if (nrow(layer_data) == 0) return() : argument is of length zero

如果您打印 tableGrob 它确实存在,所以我不确定这里发生了什么。如果您注释掉annotation_custom它的工作原理,我想我正在关注文档。谢谢。(ggplot2_0.9.3)

4

1 回答 1

3

这是您的问题的解决方案:我将您的位置data=aes_string呼叫转移到主要ggplot呼叫。我不知道为什么这很重要,但现在情节打印没有错误。

p <- ggplot(data=data, aes_string(x=fac1, y=res, color=fac2, group=fac2)) + 
     geom_point() +
     annotation_custom(myt)

在此处输入图像描述

于 2013-01-18T06:15:17.170 回答