【问题标题】:How to annotate a reference line at the same angle as the reference line itself?如何以与参考线本身相同的角度注释参考线?
【发布时间】:2020-11-20 06:59:27
【问题描述】:

我需要找到一种方法,以与参考线本身相同的角度注释参考线。

下面的语句将产生参考线和上面的标签。但是,线的斜率可能会改变,我需要找到一种方法来确保注释始终处于相同的角度。

plot(1:10,1:10) 
abline(a=8, b=-1)
text(x=4, y=5, "reference line label", srt=-28)

在 R 中有一种简单的方法吗? 提前致谢

【问题讨论】:

    标签: r


    【解决方案1】:

    一种方法是使用asp 参数设置绘图纵横比,然后使用指定的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))
    

    设置不同的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))
    

    【讨论】:

      【解决方案2】:

      @Andrie 回答的附录:不是第一次在绘图中硬编码纵横比以获得相对坐标比例,而是可以使用以下函数恢复当前工作纵横比:

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

      所以你可以创建你的情节:设置asp &lt;- getCurrentAspect();并继续 @Andrie 的其余解决方案。

      据我所知,这个函数存在于 R 生态系统的某个地方,但我还没有看到它......

      【讨论】:

      【解决方案3】:

      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)
      

      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)
      

      【讨论】:

      • 我尝试了类似的解决方案,但无法正常工作。仅供参考,您的代码在我的机器上不起作用 - 标签与线的斜率不同。
      • 安德烈,这个答案不会错过你关于纵横比的观点吗??
      • 我没有调整两个图中标签的实际位置,但角度确实与参考线匹配。
      • PS:@Andrie 不知道为什么这段代码不能在你的机器上运行。我的session info 如果有帮助的话。我的.rprofile 中有一个函数可以删除默认的ggplot2 主题,但这里没有其他不同。
      • @Maiasaura 好像您的默认绘图设备是方形的。我的是长方形的。如果您更改绘图设备的形状,绘图是否仍然有效?
      【解决方案4】:

      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
      

      带角度的文字:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多