Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 711
ChetanMV Avatar asked May 16 '17 22:05

ChetanMV


People also ask

How do you annotate a graph in R?

If you want to annotate your plot or figure with labels, there are two basic options: text() will allow you to add labels to the plot region, and mtext() will allow you to add labels to the margins. For the plot region, to add labels you need to specify the coordinates and the label.

How do I add labels in Ggplot?

To add labels at specified points use annotate() with annotate(geom = "text", ...) or annotate(geom = "label", ...) . To automatically position non-overlapping text labels see the ggrepel package.

Which argument can be used to add labels in Ggplot?

Method 1: Using geom_text() This method is used to add Text labels to data points in ggplot2 plots.

What does annotate function do in R?

Add shapes with annotate() The annotate() function allows to add all kind of shape on a ggplot2 chart. The first argument will control what kind is used: rect or segment for rectangle, segment or arrow.


1 Answers

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.

like image 180
Richard Telford Avatar answered Sep 23 '22 03:09

Richard Telford