rggplot2plot

How can I place a text on a plot (ggplot2) without knowing the exact coordinates of the plot?


I have a plot g produced with:

library(ggplot2)

g = ggplot(mtcars, aes(mpg, cyl)) +
        geom_point()

Now, I want to add a text to the plot using annotate (or anything else). I specifically want the text to appear in the lower left of the plot.

This works:

g + annotate("text", x = 12, y = 4, label = "Boring Label")

enter image description here

However, the problem with this approach is that I have to know the plot coordinates (x = 12, y = 4) in order to place the text on the lower left of the plot. I will automate this process for many different plots, and I want to place the same text in the same location (lower left) without knowing the minimum and maximum coordinates of the plot. For example, something like c(0.3, 0.1) or c(x = 0.3, y = 0.1) (0 = minimum, 1 maximum for x and y) would be very helpful. But this does not work with annotate("text", x = 0.3, y = 0.1, label = "Boring Label").


Solution

  • You can specify text position in npc units using library(ggpp):

    g + ggpp::geom_text_npc(aes(npcx = x, npcy = y, label=label), 
                      data = data.frame(x = 0.05, y = 0.05, label='Boring label'))
    

    enter image description here