I wish to position text in a ggplot
without specifying x
and y
positions, but instead using keywords, like e.g. in graphics::leg
The solution using infinity is good and is definitely the easiest option.
However, if you want more control over the position of your labels (for example, if you want them centered, or if you want more space between the axis line and annotation), you can use some math with min()
and max()
of your plot titles to create centered titles at top, bottom, right, or left. The code below is a bit lengthy, but will still place labels correctly if the values in your plot change. Also, to copy to other plots, you won't need to manually calculate values, just change the names of the x and y variables.
sp <- ggplot(mpg, aes(hwy, cty)) +
geom_point() +
theme_classic() +
annotate("text", label = "top",
x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = max(mpg$cty), vjust = 1) +
annotate("text", label = "bottom",
x = 0.5*(min(mpg$hwy) + max(mpg$hwy)), y = min(mpg$cty), vjust = 0) +
annotate("text", label = "right",
x = max(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 1) +
annotate("text", label = "left",
x = min(mpg$hwy), y = 0.5*(min(mpg$cty) + max(mpg$cty)), hjust = 0)
sp