24

I am looking to add a small white text box, with custom text in the body of my ggplot plot. The text I want to add is to identify a horizontal line I am adding to the plot.

  ggplot(cb_emp) +  
  geom_point(aes(x = grossunits, 
                 y = rate, 
                 color = as.factor(outlier))
                 , alpha = 1/4) +
  scale_color_discrete(name  ="Outcome",
                        breaks=c(0, 1),
                        labels=c("Not outlier", "Outlier")) +
  geom_hline(aes(yintercept = meancbrate)) + 
  geom_vline(aes(xintercept = meanac) +
  annotate("text", x = max(grossunits), y = meancbrate, label = "avg rate")  

Here is the plot I get:

enter image description here

Here is the plot I want (or something like this):

enter image description here

Please let me know if there is an easy way of achieving this.

Greatly appreciate the help!

neilfws
  • 32,751
  • 5
  • 50
  • 63
ChetanMV
  • 255
  • 1
  • 2
  • 5
  • try `geom_label(x = max(grossunits), y = meancbrate, label = "avg rate")` – ahly May 16 '17 at 22:33
  • thanks for the quick reply @ahly! I tried it, however, I get no plot... it doesn't render. And, my R Studio instance hangs. Maybe it is trying to label all the points? I have about 25k points – ChetanMV May 16 '17 at 22:43
  • calculate the x and y values where the label is to be displayed outside of the ggplot command. Then do something like `geom_label(x = x_lab, y = y_lab, label = "avg rate")`, where `x_lab` and `y_lab` refers to the position where you want the labels – ahly May 16 '17 at 22:46
  • geom_label seems to require as many labels as there are points so this does not work - annotate seems to be able to do this but does not provide and option for a box around the annotated text – Markm0705 May 21 '22 at 08:43

1 Answers1

37

You can simply change to

annotate("label", x = max(grossunits), y = meancbrate, label = "avg rate") 

which will use geom_label rather than geom_text and so you get a rectangle around the label.

Richard Telford
  • 9,558
  • 6
  • 38
  • 51