代码之家  ›  专栏  ›  技术社区  ›  user1424739

如何改进沿轴线对齐文本的方式?复制

  •  0
  • user1424739  · 技术社区  · 3 年前
    y = x = seq(11)-1
    plot(x, y, type='n')
    {
      a=0; b=.5
      abline(a=a, b=b)
      x_abline = mean(par('usr')[1:2])
      y_abline = a+b*x_abline
      text(x=x_abline, y=y_abline, sprintf('abline(a=%g, b=%g)', a, b), srt=atan(b)/2/pi*360, pos=3)
    }
    {
      a=0; b=1
      abline(a=a, b=b)
      x_abline = mean(par('usr')[1:2])
      y_abline = a+b*x_abline
      text(x=x_abline, y=y_abline, sprintf('abline(a=%g, b=%g)', a, b), srt=atan(b)/2/pi*360, pos=3)
    }
    {
      a=0; b=2
      abline(a=a, b=b)
      x_abline = mean(par('usr')[1:2])
      y_abline = a+b*x_abline
      text(x=x_abline, y=y_abline, sprintf('abline(a=%g, b=%g)', a, b), srt=atan(b)/2/pi*360, pos=3)
    }
    

    我正在尝试将文本与基线对齐。但他们似乎并不完全一致。我不知道为什么会这样。有人能告诉我如何解决这个问题吗?

    enter image description here

    没有解决方案 How to annotate a reference line at the same angle as the reference line itself? 都很好。

    以下内容过于冗长。

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

    其他用于 ggplot2 ,与我的问题无关。

    以下使用 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))
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   Ben Bolker    3 年前

    文本旋转与线条的斜率不匹配的原因是您没有考虑到绘图的纵横比。

    我不确定问题的解决方案是什么 here “太过冗长”。下面的解决方案添加了三行代码来计算纵横比(而不是链接解决方案中的5,因为它定义了一个函数,所以需要更长的时间)。每次呼叫 text() 添加 *asp 在中 srt= 论点与最初帖子的23行相比,整个帖子现在有13行长。。。

    y = x = seq(11)-1
    plot(x, y, type='n')
    uy <- diff(grconvertY(1:2,"user","inches"))
    ux <- diff(grconvertX(1:2,"user","inches"))
    asp <- uy/ux
    f <- function(b, a=0) {
        abline(a=a, b=b)
        x_abline = mean(par('usr')[1:2])
        y_abline = a+b*x_abline
        text(x=x_abline, y=y_abline, sprintf('abline(a=%g, b=%g)', a, b),
             srt=atan(b*asp)/2/pi*360, pos=3)
    }
    f(b=0.5); f(b=1); f(b=2)