How to annotate a reference line at the same angle as the reference line itself?

前端 未结 4 332
情歌与酒
情歌与酒 2020-12-03 05:24

I need to find a way to annotate a reference line at the same angle as the reference line itself.

The following statement will produce the reference line and the la

相关标签:
4条回答
  • 2020-12-03 06:06

    Working example for ggplot2:

    slope<-1.3
    asp<-1
    p <- ggplot()
    p<-p+scale_x_continuous(limits = c(1, 15), expand = c(0, 0)) 
    p<-p+scale_y_continuous(limits = c(-8, 20), expand = c(0, 0)) 
    p<-p+geom_abline(intercept = 0, slope = slope)
    p<-p+coord_fixed(asp)
    p<-p+annotate("text", label = "reference line label", x = 3.5, y = 5,  colour = "red",angle=atan(slope*asp)*180/pi)
    p
    

    text with angle:

    0 讨论(0)
  • 2020-12-03 06:12

    A similar solution with ggplot2

    data <- data.frame(x = 1:10, y = 1:10)
    intercept <- 10
    slope <- -1
    ggplot(data, aes(x,y)) + geom_point(shape=1) +  
      geom_abline(intercept = intercept, slope = slope) + 
      geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi)
    

    with slope 1

    intercept <- 10
    slope <- -2
    ggplot(data, aes(x,y)) + geom_point(shape=1) +  
      geom_abline(intercept = intercept, slope = slope) + 
      geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi)
    

    with slope 2

    0 讨论(0)
  • 2020-12-03 06:19

    One way is by setting the plot aspect ratio, using the asp argument, and then to calculate the angles using the specified asp:

    asp <- 2
    
    plot(1:10,1:10, asp=asp) 
    abline(a=8, b=-1)
    text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp))
    
    abline(a=4, b=-2)
    text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp))
    

    enter image description here

    Setting a different asp:

    asp <- 0.8
    
    plot(1:10,1:10, asp=asp) 
    abline(a=8, b=-1)
    text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp))
    
    abline(a=4, b=-2)
    text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp))
    

    enter image description here

    0 讨论(0)
  • 2020-12-03 06:30

    An addendum to @Andrie's answer: instead of hard-coding the aspect ratio in the plot the first time to get the relative coordinate scales, you can recover the current working aspect ratio with the following function:

    getCurrentAspect <- function() {
       uy <- diff(grconvertY(1:2,"user","inches"))
       ux <- diff(grconvertX(1:2,"user","inches"))
       uy/ux
    }
    

    So you can create your plot: set asp <- getCurrentAspect(); and proceed with the rest of @Andrie's solution.

    For all I know this function exists somewhere in the R ecosystem, but I haven't seen it ...

    0 讨论(0)
提交回复
热议问题