2013-04-23 28 views
5

Một trong những nhu cầu chú thích một dòng trong một lô log-lin. Làm thế nào để bạn làm cho chuỗi văn bản (ở đây "0000000000") song song với dòng nó là chú thích?Làm thế nào để làm cho geom_text() song song với geom_segment() trong thang đo log-lin?

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() 
+0

Có vẻ như thế này là rất khó khăn (thậm chí không có quy mô log) trừ khi bạn khắc phục tỉ lệ bằng cách xác định 'coord_fixed (tỷ lệ = ) '. ** [Hãy xem tại đây **] (https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/1OgeP4YBoJo) – Arun

Trả lời

1

Giải pháp là như sau

require(ggplot2) 
require(scales) 
coord_ratio = ((1+sqrt(5))/2)^-1 
data <- data.frame(x=c(1:10),y=10^(1:10)) 
line_coord <- data.frame(x=round(runif(5,1,5)), 
        y=round(runif(5,10^1,10^5)), 
        xend=round(runif(5,5,10)), 
        yend=round(runif(5,10^5,10^10))) 
line_draw <- geom_segment(data=line_coord,aes(x=x,y=y,xend=xend,yend=yend),color="blue") 
angle = atan((log10(line_coord$yend)*(coord_ratio)-log10(line_coord$y)*coord_ratio)/(line_coord$xend-line_coord$x))*(180/pi) 
text <- annotate("text",x=line_coord$x,y=line_coord$y,label="LLLLLLLLLL",angle=angle,hjust=-0.1,vjust=-0.5) 
qplot(data$x,data$y) + scale_y_log10() + coord_fixed(ratio=coord_ratio) + line_draw + text 

result: i.imgur.com/0JBGAiO.png

3

Dưới đây là một cách để làm điều này bằng 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


Để có được nó để đăng nhập quy mô, nó có vẻ hơi phức tạp hơn:

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

+1

Cảm ơn bạn đã nhập. Nó dẫn tôi đến giải pháp đúng. – ifett

Các vấn đề liên quan