R: How can I annotate ggplot with a text box?

I want to add a small white text box with custom text in the body of my ggplot chart. The text I want to add is to define the horizontal line that 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 to achieve this.

Thank you for your help!

+4
source share
1 answer

You can just change to

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

which will use geom_label, not geom_text, and you will get a rectangle around the label.

+10
source

Source: https://habr.com/ru/post/1677302/


All Articles