I am developing a graphic with ggplot2 wherein I need to superimpose text over other graphical elements. Depending on the color of the elements underlying the text, it can b
Instead of adding a bounding box, I would suggest changing the text color to white which can be done by doing
Plot <- Plot +
geom_text(data = TextFrame, aes(x = X, y = Y, label = LAB), colour = 'white')
The other approach would be to add an alpha to geom_point to make it more transparent
Plot <- Plot + geom_point(size = 20, alpha = 0.5)
EDIT. Here is a way to generalize Chase's solution to automatically compute the bounding box. The trick is to add the width and height of text directly to the text data frame.
Here is an example
Labels <- c("Alabama", "Alaska", "Arizona", "Arkansas",
"Pennsylvania + California")
TextFrame <- data.frame(X = 4:8, Y = 4:8, LAB = Labels)
TextFrame <- transform(TextFrame,
w = strwidth(LAB, 'inches') + 0.25,
h = strheight(LAB, 'inches') + 0.25
)
ggplot(data = SampleFrame,aes(x = X, y = Y)) +
geom_point(size = 20) +
geom_rect(data = TextFrame, aes(xmin = X - w/2, xmax = X + w/2,
ymin = Y - h/2, ymax = Y + h/2), fill = "grey80") +
geom_text(data = TextFrame,aes(x = X, y = Y, label = LAB), size = 4)
