Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 annotate layer position in R

Tags:

r

ggplot2

In my plot I have both legends and text annotations. For legends, I can specify

legend.justification=c(1,0), legend.position=c(1,0)

to locate the position relative to the plotting region (e.g. topright, bottomleft). However, when I put an annotate layer (http://docs.ggplot2.org/0.9.3.1/annotate.html), it seems that I can only specify the coordinates of the text

annotate("text", x = 8e-7, y = 1e-5, label=data.note, size = 5)

instead of the position of the plotting region (I want to put the text in the bottomleft corner). The length of the text (label) may vary for different plots. Is there a way to achieve this? Thanks!

like image 552
alittleboy Avatar asked Mar 18 '14 18:03

alittleboy


People also ask

How do you annotate a point in R?

Adding text 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 a note in ggplot2?

You can use the annotate() function to add text to plots in ggplot2. where: x, y: The (x, y) coordinates where the text should be placed. label: The text to display.

What does annotate function do in R?

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.


2 Answers

Is this what you're looking for??

set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df, aes(x,y)) +geom_point()+
  annotate("text",x=min(df$x),y=min(df$y),hjust=.2,label="Text annotation")

There will probably be a bit of experimentation with hjust=... needed to get this exactly at the bottom left.

like image 113
jlhoward Avatar answered Oct 20 '22 15:10

jlhoward


You can use the fact that -Inf and Inf will get mapped to the extremes of the position scales without extending them to place it in the bottom left corner. hjust and vjust are needed to make the reference point the lower left corner of your text. [using jlhoward's mock data.]

set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))

ggplot(df, aes(x,y)) +geom_point()+
  annotate("text",x=-Inf,y=-Inf,hjust=0,vjust=0,label="Text annotation")

enter image description here

like image 31
Brian Diggs Avatar answered Oct 20 '22 15:10

Brian Diggs