CFD
CFD

Reputation: 198

Position ggplot geom_label as a proportion of axis limits

I would like to format a ggplot such that a geom_label is in the same vertical position in the panel regardless of the y limits, e.g. place the label 10% of the panel height from the panel bottom. Is there a straightforward way of doing this that doesn't involve creating a dataframe of label positions in advance?

Upvotes: 2

Views: 574

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

Yes. You can use annotation_custom. Let's load ggplot2 and create some data first:

library(ggplot2)

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

Now we will create a plot with a custom text annotation. The text annotation has to be a "textGrob", and we specify the units as "npc". In this case, we will draw some red text which is always at 90% of the plot's x axis and 90% of its y axis:

p <- ggplot(df, aes(x, y)) + 
  geom_point() +
  annotation_custom(grid::textGrob(label = "my label",  
                                   x = unit(0.9, "npc"), 
                                   y = unit(0.9, "npc"),
                                   gp = grid::gpar(col = "red")))
p

If we draw this again with different x (or y) limits, the label stays in the same place relative to the rest of the plot:

p + xlim(c(0, 50))

Created on 2020-09-15 by the reprex package (v0.3.0)

Upvotes: 4

Related Questions