ggplot2:annotation_custom给出一个空的图层 [英] ggplot2: annotation_custom gives an empty layer

查看:403
本文介绍了ggplot2:annotation_custom给出一个空的图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些测试数据:

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

 fac1(公式[NULL],data = NULL){

res< - as.character < - as.character(公式[[3]] [2])
fac2 < - as.character(公式[[3]] [3])

计数< - count(data,vars = c(fac2,fac1))#获取表数据准备好
colnames(计数)<-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)#注释掉,它可以工作
}

运行它:

  require(plyr)
要求(gridExtra)
要求(ggplot2)
tmp <-tf(公式= r〜f1 * f2,data = ltd)
print(tmp)

给出 if(nrow(layer_data)== 0)中的错误return():argument长度为零



如果您打印出tableGrob,它确实存在,所以我不确定这里发生了什么。如果你注释掉 annotation_custom ,它就会起作用,我想我正在关注这些文档。谢谢。 (ggplot2_0.9.3)

解决方案

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

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


Some test data:

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

And a minimal function:

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
}

Run it:

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

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

If you print the tableGrob it does exist, so I'm not sure what's going on here. If you comment out the annotation_custom it works, and I think I'm following the docs. Thanks. (ggplot2_0.9.3)

解决方案

Here is solution to your problem: I relocated your data= and aes_string call to the main ggplot call. I don't know why it matters, but now the plot prints without error.

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

这篇关于ggplot2:annotation_custom给出一个空的图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆