2014-03-18 170 views
4

在我的情节中,我有两个图例和文字注释。对于传说,我可以指定ggplot2注释R中的图层位置

legend.justification=c(1,0), legend.position=c(1,0)

相对于所述绘制区域的位置来定位(例如topright,BOTTOMLEFT)。然而,当我把一个注释层(http://docs.ggplot2.org/0.9.3.1/annotate.html),看来我只能指定文字的坐标

annotate("text", x = 8e-7, y = 1e-5, label=data.note, size = 5)

,而不是绘制区域的位置(我想提出的文本左下角)。文本的长度(label)对于不同的地块可能会有所不同。有没有办法做到这一点?谢谢!

回答

3

这是你在找什么?

set.seed(1) 
df <- data.frame(x=rnorm(100),y=rnorm(100)) 
ggplot(df, aes(x,y)) +geom_point()+ 
    annotate("text",x=min(df$x),y=min(df$y),hjust=.2,label="Text annotation") 

有可能会是一个实验位与在左下角正是得到这个需要hjust=...

4

您可以使用-InfInf将被映射到位置比例极值的事实,而不会将它们扩展为将其放置在左下角。需要hjustvjust才能使参考点位于文本的左下角。 [使用jlhoward的模拟数据。]

set.seed(1) 
df <- data.frame(x=rnorm(100),y=rnorm(100)) 

ggplot(df, aes(x,y)) +geom_point()+ 
    annotate("text",x=-Inf,y=-Inf,hjust=0,vjust=0,label="Text annotation") 

enter image description here

4

的 “天道酬勤” 的解决方案有问题,当你想多行文本。另外,文本和面板边缘之间没有空白,这很丑陋。另一个解决方案要求明确提及不好的数据。

使用annotation_custom(或者在我的示例中,直接使用proto Geom)可以很好地实现所需的效果。您可以配置边距,文本和框对齐。 以下代码中的额外好处是您可以指定使用facets=data.frame(cat1='blue', cat2='tall')之类的内容进行注释的方面。

library("ggplot2") 
annotate_textp <- function(label, x, y, facets=NULL, hjust=0, vjust=0, color='black', alpha=NA, 
          family=thm$text$family, size=thm$text$size, fontface=1, lineheight=1.0, 
          box_just=ifelse(c(x,y)<0.5,0,1), margin=unit(size/2, 'pt'), thm=theme_get()) { 
    x <- scales::squish_infinite(x) 
    y <- scales::squish_infinite(y) 
    data <- if (is.null(facets)) data.frame(x=NA) else data.frame(x=NA, facets) 

    tg <- grid::textGrob(
    label, x=0, y=0, hjust=hjust, vjust=vjust, 
    gp=grid::gpar(col=alpha(color, alpha), fontsize=size, fontfamily=family, fontface=fontface, lineheight=lineheight) 
) 
    ts <- grid::unit.c(grid::grobWidth(tg), grid::grobHeight(tg)) 
    vp <- grid::viewport(x=x, y=y, width=ts[1], height=ts[2], just=box_just) 
    tg <- grid::editGrob(tg, x=ts[1]*hjust, y=ts[2]*vjust, vp=vp) 
    inner <- grid::grobTree(tg, vp=grid::viewport(width=unit(1, 'npc')-margin*2, height=unit(1, 'npc')-margin*2)) 

    layer(
    data = NULL, 
    stat = StatIdentity, 
    position = PositionIdentity, 
    geom = GeomCustomAnn, 
    inherit.aes = TRUE, 
    params = list(
     grob=grid::grobTree(inner), 
     xmin=-Inf, 
     xmax=Inf, 
     ymin=-Inf, 
     ymax=Inf 
    ) 
) 
} 

qplot(1:10,1:10) + annotate_text2('some long text\nx = 1', x=0.5, y=0.5, hjust=1)