Ggplot2 fixes the position of the layer in R

In my story, I have both legends and text annotations. For legends I can indicate

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

to find the position relative to the plot area (for example, topright, bottomleft). However, when I add the annotated layer ( http://docs.ggplot2.org/0.9.3.1/annotate.html ), it seems that I can specify only the coordinates of the text

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

instead of the position of the plot area (I want to put the text in the bottom corner). Text length ( label) may vary for different graphs. Is there any way to achieve this? Thank!

+4
source share
3 answers

Is this what you are looking for?

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=..., .

+3

, -Inf Inf , , . hjust vjust , . [ jlhoward mock.]

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

"Inf" , . , , . , .

The desired effect can be achieved beautifully with annotation_custom (or in my example, proto Geom directly). You have custom field size, text and field. An added bonus in the following code is that you can specify which facet to annotate with something like 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)
+4
source

Source: https://habr.com/ru/post/1532352/


All Articles