aligning text in geom_text?

10,047 views
Skip to first unread message

Roey Angel

unread,
May 9, 2012, 4:19:43 AM5/9/12
to ggp...@googlegroups.com
Hi,
I was wondering if there's a way to align text when using geom_text.
Left-centre-right will do for me but I just couldn't find anything like that in the documentation.

Here's an example that would show where it's necessary (code taken mostly from: http://stackoverflow.com/questions/7201067/showing-variable-labels-under-the-segments-of-dendrogram-with-ggdendro):

library(ggplot2)
library(ggdendro)
data(mtcars)
x <- as.matrix(scale(mtcars))
dd.row <- as.dendrogram(hclust(dist(t(x))))
ddata_x <- dendro_data(dd.row)

p <- ggplot(segment(ddata_x)) +
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend)) +
   scale_y_continuous(trans = 'reverse')
p + geom_text(data=label(ddata_x), aes(label=label, x=x, y=0)) +
  coord_flip()

It would look much nicer if I could align all the labels on the leaves to the left.

Thanks in advance,
Roey

dendro_w.label.png

Brandon Hurr

unread,
May 9, 2012, 5:28:36 AM5/9/12
to Roey Angel, ggp...@googlegroups.com

p + geom_text(data=label(ddata_x), aes(label=label, x=x, y=0), hjust=0) + 

  coord_flip()

HTH, 

B



--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Roey Angel

unread,
May 9, 2012, 5:56:24 AM5/9/12
to ggp...@googlegroups.com
Thanks for the quick reply Brandon, but that doesn't really solve it properly.
One problem is that the alignment to the left works only for hjust=0; if you plug in different values in hjust the alignment is lost.
The second issue is that this allows only for left alignment but not right or centre.

Thanks again though
Roey



Brandon Hurr

unread,
May 9, 2012, 5:58:28 AM5/9/12
to Roey Angel, ggp...@googlegroups.com
When you say Right and center, which right/left and center are you referring to? the whole plot, x=0 or something else? Could you draw what you want? I'm a bit confused. 

Roey Angel

unread,
May 9, 2012, 6:23:10 AM5/9/12
to ggp...@googlegroups.com
ok Brandon thanks to your question I got it right.
I can use hjust to align the text relative to each other (0 for left 1 for right, nothing for centre) and then use the x y values for shifting it around.

Thanks again for the help
Roey
Reply all
Reply to author
Forward
0 new messages