在R中使用ggplot2注释图层位置

13

在我的图表中,我既有图例又有文本注释。对于图例,我可以指定

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个回答

16

您可以利用-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")

这里输入图片描述


12

这是你要找的吗?

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=... 进行一些实验。


6
"Inf" 解决方案在处理多行文本时存在问题。此外,文本和面板边缘之间没有间距,很不美观。另一个解决方案需要显式提及数据,这也不好。使用 annotation_custom (或者像我例子中的 proto Geom 一样) 可以很好地实现所需效果。你可以配置边距、文本和框对齐方式。以下代码的额外奖励是,你可以指定要注释的 facet,例如 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接