Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make geom_text() parallel to geom_segment() in a log-lin scale?

Tags:

r

ggplot2

One needs to annotate a line in a log-lin plot. How do you make the text string (here "0000000000") parallel to the line it is annotating?

require(ggplot2)
require(scales)
x=c(1:10)
y=2^x
data_line <- data.frame(x=3,xend=8,y=2^8,yend=2^9)
line <- geom_segment(data=data_line,aes(x=x,xend=xend,y=y,yend=yend),color="blue")
angle= atan((data_line$yend - data_line$y) / (data_line$xend - data_line$x))*(180/pi)
text <- annotate("text",x=data_line$x,y=data_line$y,label="0000000000",angle=angle)
qplot(x=x,y=y,geom="line") + line + text + scale_y_log10()
like image 263
ifett Avatar asked Apr 23 '13 10:04

ifett


1 Answers

Here's one way to do this using coord_fixed:

ratio <- .25/(256/5) # 256/5 is from (512-256)/(8-3)
df1 <- data.frame(x = 1:10, y = 2^(1:10))
d <- data.frame(xmin=3, xmax=8, ymin=256, ymax=512, annotation="bla")
ggplot() + geom_line(data = df1, aes(x=x, y=y)) + 
    geom_segment(data=d, aes(x=xmin, xend=xmax, y=ymin, yend=ymax)) + 
    geom_text(data = d, aes(x=4, y=256/5 * 4 + 512/5, 
    label=annotation, angle=atan2((ymax-ymin)*ratio, 
    (xmax-xmin)) * 180/pi), vjust=-0.5) + coord_fixed(ratio=ratio)

enter image description here


To get it to log scale, it seems a bit more tricky:

ratio <- -log10(.25/(256/5)) # 256/5 is from (512-256)/(8-3)
df1 <- data.frame(x = 1:10, y = 2^(1:10))
d <- data.frame(xmin=3, xmax=8, ymin=256, ymax=512, annotation="bla")
ggplot() + geom_line(data = df1, aes(x=x, y=y)) + 
    geom_segment(data=d, aes(x=xmin, xend=xmax, y=ymin, yend=ymax)) + 
    geom_text(data = d, aes(x=4, y=256/5 * 4 + 512/5, 
    label=annotation, angle=log10(atan2((ymax-ymin)*ratio, 
    (xmax-xmin)) * 180/pi)), vjust=-0.5) + coord_fixed(ratio=ratio) + scale_y_log10()

enter image description here

like image 173
Arun Avatar answered Oct 15 '22 21:10

Arun