Skip to contents

One can specify the relative position of the figure easily. Configurable margin, text and box justification. The 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')

From Stack Overflow comment https://stackoverflow.com/questions/22488563/ggplot2-annotate-layer-position-in-r

Usage

annotate_textp(
  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,
  box_just = ifelse(c(x, y) < 0.5, 0, 1),
  margin = unit(size/2, "pt"),
  thm = ggplot2::theme_get()
)

Arguments

label

A string. The text to be plotted.

x

Numeric. X axis position (min=0, max=1 - relative to the plot margins)

y

Numeric. Y axis position (min=0, max=1 - relative to the plot margins)

hjust

Numeric. The horizontal alignment (0 = left, 0.5 = center, 1 = right). Default=0

alpha

Numeric. Transparency (0:1). Default=NA

size

Numeric. Font size. Default=theme default

Value

Returns a geom layer

Author

Rosen Matev

Examples

p1 = ggplot2::ggplot(data.frame(x=1:10,y=1:10), ggplot2::aes(x,y)) + ggplot2::geom_point()
p1 + annotate_textp('Text annotation\nx=1, y=0, hjust=1', x=1, y=0, hjust=1)
#> Error in unit(1, "npc"): could not find function "unit"
p1 + annotate_textp('Text annotation\nx=0.1, y=0.9, hjust=0', x=0, y=1, hjust=0)
#> Error in unit(1, "npc"): could not find function "unit"
p1 + annotate_textp('Text annotation\nx = 0.5, y=0.5, hjust=0.5\nbox_just=c(0.5,0.5)', x=0.5, y=0.5, hjust=0.5, box_just=c(0.5,0.5))
#> Error in unit(1, "npc"): could not find function "unit"
p1 + annotate_textp('Text annotation\nx = 0.5, y=0.5, hjust=0.5\nbox_just=c(0.5,0.5)\nsize=14, alpha=0.5', x=0.5, y=0.5, hjust=0.5, box_just=c(0.5,0.5), size=14, alpha=0.5)
#> Error in unit(1, "npc"): could not find function "unit"