Search code examples
rplotscale

How to rescale label on x axis in log2(n+1) format?


I want to format my x-axis in log2(n+1) format so the x-axis labels correspond to 1, 2, 4, 16 and so on.

Input:

x <- c(1, 2, 3, 11, 15)
y <- c(1.1, 1.2, .4, 2.1, 1.5)

plot(log2(x + 1), y, axes=FALSE)
axis(1, at=(labels=as.character(formatC(x))), cex.axis=0.9)

But plot I get still has the original x-axis values.

enter image description here

How can I make my x-axis powers of 2 (1, 2, 4, 16, etc.)?


Solution

  • I guess this is what you want.

    x<-c(1,2,3,11,15) 
    y<-c(1.1,1.2,.4,2.1,1.5)
    lab<-c(1,2,4,16)
    plot(log2(x+1),y,xaxt="n",xlab="x")
    axis(1,at=log2(lab+1),labels=lab)
    

    It might also be useful to calculate equally spaced labels:

    lab<-round(2^seq(min(log2(x+1)),max(log2(x+1)),length.out=4)-1)