Get margin line locations (mgp) in user coordinates

前端 未结 1 1501

I am trying to do some non-conventional plot labeling and would like a way to convert the line parameter in mtext and axis to user coo

1条回答
  •  春和景丽
    2020-12-05 20:33

    The following should do the trick:

    setup_plot()
    abline(v=par('usr')[1] - (0:9) * 
             diff(grconvertX(0:1, 'inches', 'user')) * 
             par('cin')[2] * par('cex') * par('lheight'), 
           xpd=TRUE, lty=2)
    

    margin_lines

    par('cin')[2] * par('cex') * par('lheight') returns the current line height in inches, which we convert to user coordinates by multiplying by diff(grconvertX(0:1, 'inches', 'user')), the length of an inch in user coordinates (horizontally, in this case - if interested in the vertical height of a line in user coords we would use diff(grconvertY(0:1, 'inches', 'user'))).

    This can be wrapped into a function for convenience as follows:

    line2user <- function(line, side) {
      lh <- par('cin')[2] * par('cex') * par('lheight')
      x_off <- diff(grconvertX(0:1, 'inches', 'user'))
      y_off <- diff(grconvertY(0:1, 'inches', 'user'))
      switch(side,
             `1` = par('usr')[3] - line * y_off * lh,
             `2` = par('usr')[1] - line * x_off * lh,
             `3` = par('usr')[4] + line * y_off * lh,
             `4` = par('usr')[2] + line * x_off * lh,
             stop("side must be 1, 2, 3, or 4", call.=FALSE))
    }
    
    setup_plot()
    abline(v=line2user(line=0:9, side=2), xpd=TRUE, lty=2)
    

    EDIT: An updated version of the function, which works with logged axes, is available here.

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