Consistent positioning of text relative to plot area when using different data sets
You can use annotation_custom
. This allows you to plot a graphical object (grob
) at specified co-ordinates of the plotting window. Just specify the position in "npc" units, which are scaled from (0, 0) at the bottom left to (1, 1) at the top right of the window:
library(ggplot2)
mpg_plot <- ggplot(mpg) + geom_point(aes(displ, hwy))
iris_plot <- ggplot(iris) + geom_point(aes(Petal.Width, Petal.Length))
annotation <- annotation_custom(grid::textGrob(label = "example watermark",
x = unit(0.75, "npc"), y = unit(0.25, "npc"),
gp = grid::gpar(cex = 2)))
mpg_plot + annotation
iris_plot + annotation
Created on 2020-07-10 by the reprex package (v0.3.0)
The ggpmisc
package has some convenience functions where coordinates are given in 'npc' graphic units.
You may try geom_text_npc
(or its sibling geom_label_npc
), "intended to be used for positioning text relative to the physical dimensions of a plot".
Create a geom_text_npc
layer:
npc_txt = geom_text_npc(aes(npcx = 0.9, npcy = 0.1, label = "some text"), size = 6)
...which then can be added to all plots:
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
npc_txt
ggplot(iris) +
geom_point(aes(Petal.Width, Petal.Length)) +
npc_txt
If you don't need the precision of the coordinates that numerical npcx
and npcy
provide, you can also specify some basic locations (corners and center) with "words" (see Specify position of geom_text by keywords like “top”, “bottom”, “left”, “right”, “center”). In your example, the words that best correspond to your numerical position would be "right"
and "bottom"
:
npc_txt = geom_text_npc(aes(npcx = "right", npcy = "bottom", label = "some text"), size = 6)
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
npc_txt
ggplot(iris) +
geom_point(aes(Petal.Width, Petal.Length)) +
npc_txt