2013-01-18 34 views
3

一些测试数据:GGPLOT2:annotation_custom给出了一个空层

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)

+0

我的猜测是,'annotation_custom'不喜欢离散轴(如'annotation_raster')。在任何情况下,您都需要指定xmin,xmax,ymin,ymax,但它在这里仍然不起作用。 – baptiste

+0

离散轴无关紧要,我用另一个版本工作。但我正在做一些改变,使用一个简单的公式界面,并符合ggplot2中的最新变化,并且它打破了。 –

回答

3

以下是解决您的问题的方法:我将您的data=aes_string调用重定位到主要的ggplot调用。我不知道它为什么重要,但现在情节打印没有错误。

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

enter image description here

+0

很好的捕获:)在函数中,myt是从计数计算的,而计数又是使用变量fac1和fac2从数据计算出来的。您的修补程序将美学fac1和fac2放置在基础图层中,因此可以在annotation_raster图层中引用这些美学效果,尽管它对我很有趣,因为myt是从计数数据框而不是数据生成的。正如布莱恩在另一篇文章中所说的那样,“每一层都需要数据和美学”:)但平心而论,错误相当微妙...... – Dennis

+0

@丹尼斯@bdemarest谢谢。我对这个问题很困惑,但它确实有效。我不确定是否可以在全功能(我没有提供)中使用这个解决方案,但我会尝试。在完整的功能中,我非常努力地将所有的图层完全分开,因为美学之间存在交集。因此,简单的'ggplot()'使整个过程无w/o默认美学。我真的试图保持(数据,美学,几何)/每一层,但是'annotation_custom'并不真正符合那个(但也许问题在于它*在底层)。 –

+0

@BryanHanson这看起来像一个bug。你的代码是合法的。这是同样的问题https://github.com/hadley/ggplot2/issues/756? –

相关问题