1

I want to plot a line with geom_line() in ggplot2 and place a text annotation with geom_text() so that the text is parallel to the line. Is there a straightforward way to figure out what angle I should specify to geom_text() so the text will be parallel to the line?

e.g.:

df <- data.frame(x=c(1,2), y=c(150, 340))
ggplot(data=df, aes(x=x,y=y)) + geom_line() + 
    geom_text(label="label", x = mean(df$x), y=mean(df$y) + 1, angle = ???)

I'm trying to figure out whether there's an expression I can put in place of "???" to automatically calculate the appropriate angle.

Taking the arctan of the slope of the line won't work because the angle in geom_text is an angle in device-space, not plotting-coordinate space: I need to specify different angles for drawing the plot on devices with different aspect ratios (e.g., png(500,500) versus png(1000,500)).

Jonathan Gilligan
  • 701
  • 1
  • 5
  • 21
  • Can you add a working example with the arctan? If you managed to make this work for, say, 1:1 ratio, I think it should be relatively easy to adjust for different aspect ratios. – tonytonov Sep 03 '14 at 06:49

1 Answers1

2

Following tonytonov's suggestion, you could probably first try to find out the aspect ratio of your device and then use this ratio in your plot with coord_fixed() (see here). You then may calculate the required angle for the text elements.

Community
  • 1
  • 1
Daniel
  • 7,252
  • 6
  • 26
  • 38