在R中给对数坐标系加上对数形式的坐标轴

这个问题其实很常见,使用minor.tick为关键词一搜就可以搜出来很多代码。

这里,我更改了http://stackoverflow.com/questions/6955440/displaying-minor-logarithmic-ticks-in-x-axis-in-r中的一些细节,形成了如下的代码。

#' @title minor ticks for logarithmic scale axis
#' @param ax an integer specifying which side of the plot the axis is to be drawn on. 
#'           The axis is placed as follows: 1=below, 2=left, 3=above and 4=right. 
#'           Exact same as side in axis.
#' @param n an integer specifying the number of minor ticks (default to 9)
#' @param t.ratio an numeric specifying the ratio between the major and the minor ticks 
#'                (default to 0.5)
#' @param mn,mx the minimum and the maximum on the logarithmic scale 
#'              (mn=0 thus means the minimum is 10^0 or 1 !)

minor.ticks.axis <- function(ax, n=9, t.ratio=0.5, mn, mx, ...){

  lims <- par("usr")
  lims <- if(ax %in% c(1,3)) lims[1:2] else lims[3:4]

  major.ticks <- pretty(lims,n=5)
  if(missing(mn)) mn <- min(major.ticks)
  if(missing(mx)) mx <- max(major.ticks)

  major.ticks <- major.ticks[major.ticks >= mn & major.ticks <= mx]

  labels <- sapply(major.ticks,function(i)
            as.expression(bquote(10^ .(i)))
          )
  axis(ax,at=major.ticks,labels=labels, las=ifelse(ax %in% c(2, 4), 2, 1), ...)

  n <- n+2
  minors <- log10(pretty(10^major.ticks[1:2],n))-major.ticks[1]
  minors <- minors[-c(1,n)]

  minor.ticks = c(outer(minors,major.ticks,`+`))
  minor.ticks <- minor.ticks[minor.ticks > mn & minor.ticks < mx]


  axis(ax,at=minor.ticks,tcl=par("tcl")*t.ratio,labels=FALSE)
}


x <- 10^(0:4)
y <- 10^(-7:-3)
plot(log10(x), log10(y), xaxt="n", yaxt="n", xlab="x", ylab="y", xlim=c(0,4), ylim=c(-7.5, -2.5))
minor.ticks.axis(1, 9, mn=0, mx=4)
minor.ticks.axis(2, 9, mn=-7, mx=-3)

plot of chunk unnamed-chunk-1

Leave a Reply

  

  

  

%d 博主赞过: