Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning text annotation in ggplot2

Tags:

r

ggplot2

Here's a test df:

a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)

I'd like to create a bar plot and add text above each bar, a certain distance beneath the top, thus I use y=Inf, vjust=2, however the letters are now aligned by their tops and not the bottom of the letter (i.e. they don't sit on the same horizontal line). Is there a way to change that (without having to fiddle around with the values to something like vjust=2.45 or so for the "shorter" ones)?

ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
  scale_y_continuous(limits = c(0,9)) +
  annotate('text', x=1, y=Inf, vjust=2, label = "a", parse=TRUE) + 
  annotate('text', x=2, y=Inf, vjust=2, label = "a", parse=TRUE) + 
  annotate('text', x=3, y=Inf, vjust=2, label = "b", parse=TRUE) + 
  annotate('text', x=4, y=Inf, vjust=2, label = "b", parse=TRUE)

enter image description here

like image 372
erc Avatar asked Sep 22 '14 11:09

erc


People also ask

How to left align text in ggplot?

hjust = 0 does what you want. hjust stands for horizontal justification, 0 will be left-justified, 0.5 will be centered, and 1 will be right-justified.

How do you left align text in R?

Left alignment can be requested by setting sep = "\\l" , right alignment by "\\r" and center alignment by "\\c" . Mind the backslashes, as if they are omitted, strings would be aligned to the character l, r or c respectively. Default value is "\\r" , thus right alignment.

What does geom_ text do?

Text geoms are useful for labeling plots. They can be used by themselves as scatterplots or in combination with other geoms, for example, for labeling points or for annotating the height of bars. geom_text() adds only text to the plot. geom_label() draws a rectangle behind the text, making it easier to read.


1 Answers

The answer is quite simple: Use a single "annotate" command instead of multiple ones. Edit: If the parse argument is set to TRUE (as in your snippet), this method fails. :) Good luck.

library(ggplot2)

a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)

ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
scale_y_continuous(limits = c(0,10)) +
# This is the difference to yor code:
annotate("text", x = 1:4, y = Inf,  vjust=2, label = c("a", "a", "b", "b"))

enter image description here

This is actually included in the R documentation of annotate: (last line of ?annotate)

p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))
like image 68
Peter Lustig Avatar answered Sep 26 '22 03:09

Peter Lustig