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

社会主义新天地 提交于 2019-12-09 09:01:13

问题


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:

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

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

Greatly appreciate the help!


回答1:


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.



来源:https://stackoverflow.com/questions/44012554/r-how-can-i-annotate-a-ggplot-with-a-text-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!