Once your ggplot2 chart is done, you often need to annotate it to provide more information or highlight a specific part. This is done using the **annotate()** function.

In this first example, we add 2 **text elements** on the plot. Please note that to add text from a data.frame, you need to use **geom_text**!

1 2 3 4 5 6 7 8 9 10 11 |
# library library(ggplot2) head(mtcars) # basic graph p=ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() # Add text on a specific positions: p + annotate("text", x = c(2,4.5), y = c(20,25), label = c("label 1", "label 2") , color="orange", size=5 , angle=45, fontface="bold") |

Now, here are 3 examples showing how to add **rectangles**, **segments** and **arrows** to your plot. The code is quite straightforward:

1 2 3 4 5 6 7 8 9 10 |
# Add rectangles p + annotate("rect", xmin=c(2,4), xmax=c(3,5), ymin=c(20,10) , ymax=c(30,20), alpha=0.2, color="blue", fill="blue") # Add segments p + annotate("segment", x = 1, xend = 3, y = 25, yend = 15, colour = "purple", size=3, alpha=0.6) # Add arrow p + annotate("segment", x = 2, xend = 4, y = 15, yend = 25, colour = "pink", size=3, alpha=0.6, arrow=arrow()) |

If you need to add **ablines**, do not use annotate! The **geom_hline** and **geom_vline** have been created for that!

1 2 3 4 |
# Add abline p + geom_hline(yintercept=25, color="orange", size=1) + geom_vline(xintercept=3, color="orange", size=1) |

Last, you can add a **point** and a **range** around it with the “**pointrange**” geom:

1 2 3 4 |
# Add point and range p + annotate("pointrange", x = 3.5, y = 20, ymin = 12, ymax = 28,colour = "orange", size = 1.5, alpha=0.4) |

Not what you are looking for ? Make a new search !

`[mediatagger]`

## Leave a Reply