1
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 5, y = 25, label = "Some looooooooooooooooooooooooooong text")

Also, I must assume that the range of the x and y axis are unknown. Hence, I can't even hardcode the x and y values like example above.

3 Answers3

0

You might be able to get what you want as described here by disabling clipping and changing the margins:

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

p + annotate("text", x = 5, y = 25,
             label = "Some looooooooooooooooooooooooooong text") +
  coord_cartesian(clip = 'off') +
  theme(plot.margin = unit(c(1,5,1,1), "lines"))

With that approach you still have to compute the size of margin needed depending on the text length and position, for example:

lbl_txt <- "Some looooooooooooooooooooooooooong text"
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 5, y = 25,
             label = lbl_txt) +
  coord_cartesian(clip = 'off') +
  theme(plot.margin = unit(c(1,(nchar(lbl_txt)-5)*2,1,1), "points"))
Alexlok
  • 2,999
  • 15
  • 20
0
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 5, hjust = 1, y = 25, label = "Some looooooooooooooooooooooooooong text")

I have found a solution. There is an hjust parameter that you can set to. 1 to Right align it, that will ensure it will not go out of the plot on the right.

0

Adding to your solution provided above, since the words in your label are separated by spaces, you can also consider using the str_wrap function from the stringr package. This could give you some extra room as the label pushes further to the left side.

library(ggplot2)
library(stringr)

label_example <- c("Some looooooooooooooooooooooooooong text")


p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 5, hjust = 1, y = 25, label = str_wrap(label_example, 1))

Created on 2020-11-16 by the reprex package (v0.3.0)

Eric
  • 2,699
  • 5
  • 17