39
votes

I used vjust as workaround and elaborate an acceptable distance by try and error. But this is sometimes very time consuming and changes with the font size and the axis scale.

Is there a better method to align the text in the example automatic?

library(ggplot2)

ggplot(data=mtcars, aes(x=hp, y=mpg))+
geom_point()+
theme_bw() +
  geom_vline(xintercept=200, colour="grey") +
  geom_text(aes(x=200, label="the strong cars", y=20), colour="blue", angle=90, vjust = 1.2, text=element_text(size=11))+
  geom_text(aes(x=200, label="the weak cars", y=20), colour="red", angle=90, vjust = -1, text=element_text(size=11))

ggsave(filename="geomline.png", width=5.5, height=2*3, dpi=300)

enter image description here

1
how do you want the alignment to be? vjust=0 and vjust=1 seem to do what they're supposed to, values outside this range are always more excentric. - baptiste
I want that the computer looks the fontsize up and places the textbox in the correct distance. So the user will not have to play around with the vjust values. - Jonas Stein
I think positioning labels automagically is going to be hard, even if the plot is always going to be a simple one. Have you looked at the directlabels package? - SlowLearner
I think directlabels goes in the right direction. But I found no way to annotate lines like in the example above. - Jonas Stein

1 Answers

44
votes

Another solution for the case of one line labels would be to add a line break before/after and keep the default vjust=0.5.

ggplot(data=mtcars, aes(x=hp, y=mpg)) +
  geom_point() +
  theme_bw() +
  geom_vline(xintercept=200, colour="grey") +
  geom_text(aes(x=200, label="\nthe strong cars", y=20), colour="blue", angle=90, text=element_text(size=11)) +
  geom_text(aes(x=200, label="the weak cars\n", y=20), colour="red", angle=90, text=element_text(size=11))