[R] tricks

October 30, 2009

Decimal log scale on a plot

Filed under: Plot — Tags: , — Timothée Poisot @ 8:30 pm

R only does natural (neperian) log scales by default, and this is lame.

Here is a simple code to do decimal log scale, pretty much a requirement for scientists…

The force(x/y)lim options works for natural and log scales (for the later case, you need to specify the power of 10 that you want : c(-2,2) fixes the limit from 0.01 to 100)

drawlogaxis <- function(side,range)
{
	par(tck=0.02)
#	d <- log(range,10)
	d <- range
	mlog <- floor(min(d))
	Mlog <- ceiling(max(d))
	SeqLog <- c(mlog:Mlog)
	Nlog <- (Mlog-mlog)+1
	axis(side,at=SeqLog,labels=10^SeqLog)
	ats <- log(seq(from=2,to=9,by=1),10)
	mod <- NULL
	for(i in SeqLog)
	{
		mod <- c(mod,rep(i,length(ats)))
	}
	ats <- rep(ats,Nlog)
	ats <- ats+mod
	par(tck=0.02/3)
	axis(side,at=ats,labels=NA)
}

logplot <- function(x,y,log='xy',...,forceylim=c(0,0),forcexlim=c(0,0))
{
	par(tck=0.02)
	xlg <- FALSE
	ylg <- FALSE
	if('x'%in%strsplit(log,'')[[1]]){x <- log(x,10);xlg=TRUE}
	if('y'%in%strsplit(log,'')[[1]]){y <- log(y,10);ylg=TRUE}
	yl <- ifelse(forceylim==c(0,0),range(y),forceylim)
	xl <- ifelse(forcexlim==c(0,0),range(x),forcexlim)
	plot(x,y,...,axes=FALSE,ylim=yl,xlim=xl)
	if(xlg){drawlogaxis(1,xl)}else{axis(1,at=pretty(xl),labels=pretty(xl))}
	if(ylg){drawlogaxis(2,yl)}else{axis(2,at=pretty(yl),labels=pretty(yl))}
	box()
}

addlog <- function(x,y,log='xy',...)
{
	xlg <- FALSE
	ylg <- FALSE
	if('x'%in%strsplit(log,'')[[1]]){x <- log(x,10);xlg=TRUE}
	if('y'%in%strsplit(log,'')[[1]]){y <- log(y,10);ylg=TRUE}
	points(x,y,...)

}
Advertisements

October 15, 2009

Filled contour with log-log scale

Filed under: Plot — Tags: , , , — Timothée Poisot @ 8:23 pm

A quick workaround to have a filled.contour plot with natural log10-log10 scale (instead of the default natural log scale)

plotmat <- function(mat,main='',factor='M',MeasuredResponse='Coexistence')
{
X <- as.numeric(rownames(mat))
Y <- as.numeric(colnames(mat))
if(factor=='C')
{
Y <- Y/0.16
}
rownames(mat) <- as.numeric(X)
colnames(mat) <- as.numeric(Y)
colorFun <- colorRampPalette(c("black","darkblue","blue","green",
"orange",'yellow',"red","darkred",'white'))

lX <- log(X, 10)
lY <- log(Y, 10)

pretty.X.at <- pretty(range(lX),n=6)
pretty.X.lab <- round(10^pretty.X.at,0)
pretty.Y.at <- pretty(lY,n=4)
pretty.Y.lab <- round(10^pretty.Y.at,2) pretty.Y.lab[pretty.Y.lab>1] <- round(pretty.Y.lab[pretty.Y.lab>1],0)
pretty.Y.lab[(pretty.Y.lab>0.1)&(pretty.Y.lab<1)] <- round(pretty.Y.lab[(pretty.Y.lab>0.1)&(pretty.Y.lab<1)],1)

filled.contour(lX,lY,mat,
axes=FALSE,
frame.plot=TRUE,
color=colorFun,
ylab= MeasuredResponse,
xlab='Time between perturbation events',
main=main,
key.title=title(main=""),
key.axes=axis(4,at=pretty(vmat)),
plot.axes={ axis(1,at=pretty.X.at,labels=pretty.X.lab)
axis(2,at=pretty.Y.at,labels=pretty.Y.lab) })
}

Create a free website or blog at WordPress.com.