R/plot_ylim_tools.R

Defines functions ylim ylim.include0 ylim.last

#' Auto generate ylim parameters for plot functions
#' 
#' The function name \code{ylim} will be masked by ggplot2 which is nowadays likely to be loaded. 
#' Therefore, use \code{.ylim()} or \code{ephys2::ylim()}.
#'
#' @param y The data to calculate the ylim parameter from (usually the y data of your plot, or proto object representing a series). 
#'
#' @return  A vector suitable for beeing used as the ylim argument in most plot commands
#' @name ylimtools
#' @examples
#' x<-rnorm(100)+12

#' par(mfrow=c(3,2))
#' p=plot(1:10,1:10*3, ylim=c(0,40), main='first plot')
#' plot(x, ylim = ylim.last(), main='same ylim as first')
#' 
#' data(st2)
#' data(st3)
#' datalist<-list(st2=st2,st3=st3)
#' 
#' ylim= .ylim(datalist)
#' lapply(names(datalist), function(n) datalist[[n]]$plot(ylim=ylim, main=paste(n, '- group 1, sharing ylim')))
#' 
#' ylim= .ylim(datalist, include0=T)
#' lapply(names(datalist), function(n) datalist[[n]]$plot(ylim=ylim, main=paste(n, '- group 2 sharing ylim with zero')))

NULL



#' @describeIn ylimtools set ylim to min-max. (Warning: will be masked by ggplot2)
#' @export
ylim <- function(y, include0 = F) {
    if (include0) {
        return(ylim.include0(y))
    }
    
    if (inherits(y, "list")) {
        return(c(min(unlist(lapply(y, function(y) min(ylim(y))))), max(unlist(lapply(y, function(y) max(ylim(y)))))))
    }
    if (inherits(y, "proto")) {
        y <- y$sweeps$y
    }
    c(min(y), max(y))
}

ylim.include0 <- function(y) {
    if (inherits(y, "list")) {
        return(c(min(unlist(lapply(y, function(y) min(ylim.include0(y))))), max(unlist(lapply(y, 
            function(y) max(ylim.include0(y)))))))
    }
    if (inherits(y, "proto")) {
        y <- y$sweeps$y
    }
    c(min(0, min(y)), max(0, max(y)))
}


#' @describeIn ylimtools same as ylim but not masked by ggplot2
#' @export
.ylim <- ylim

#' @describeIn ylimtools set ylim identical to last plot
#' @export
ylim.last <- function() {
  par("usr")[3:4]
}
tdanker/ephys2 documentation built on Aug. 11, 2019, 12:12 p.m.