Search code examples
raxisscaling

Linear function axis scaling in R


I have the following function

C=15
S=seq(0,12,.1)
pA=1
pS=0.5

    
    A <- function(S) (C/pA)-(pA/pS)*S
    
    plot (S, A(S), type="l", col="red", ylim=c(0,15), xlim=c(0,15), xlab="S", ylab="A")
    text(8, 11.5, "Function", col = "red", cex=.9)
    text(11, 10.2, expression(A==frac(C,p[S])-frac(p[A],p[S])%.%S), cex=.9, col = "red")
    grid()

How can I scale the axis so that I can "zoom out" a bit. I am looking for a function similar to ylim but where I could say: ylim=c(0,15, by=1).


Solution

  • Update

    It seems your "zoom out" is meant for the grid lines, not for the axis or anything. I'll keep the previous answer below, but this should address it, I think.

    # no change yet
    plot (S, A(S), type="l", col="red", ylim=c(0,15), xlim=c(0,15), xlab="S", ylab="A")
    text(8, 11.5, "Function", col = "red", cex=.9)
    text(11, 10.2, expression(A==frac(C,p[S])-frac(p[A],p[S])%.%S), cex=.9, col = "red")
    # no call to grid, since we want to control it a little more precisely
    abline(h = seq(0, 15), col = "lightgray", lty = "dotted", lwd = par("lwd"))
    abline(v = seq(0, 15, by = 5), col = "lightgray", lty = "dotted", lwd = par("lwd"))
    

    plot with grid lines more precisely defined

    You can do just abline(h=seq(...)) and not set col=, lty=, or lwd=, but realize that abline's default values are different from grid's defaults. I used those values to mimic grid's look and feel.


    Old answer

    I think you mean to change the y axis labels, not the y axis limits (which is all that ylim= can effect).

    Using base R graphics:

    plot (S, A(S), type="l", col="red", ylim=c(0,15), xlim=c(0,15), xlab="S", ylab="A",
          yaxt = "n") # this is new
    text(8, 11.5, "Function", col = "red", cex=.9)
    text(11, 10.2, expression(A==frac(C,p[S])-frac(p[A],p[S])%.%S), cex=.9, col = "red")
    grid()
    axis(2, at = 1:15, las = 2)
    

    enter image description here

    Explanation:

    • plot(..., yaxt = "n") means to not plot the y-axis ticks and labels, see ?par.
    • axis(...) adds an axis to a side. By itself, it will just add a default axis.
    • at= sets where the ticks and labels are placed.
    • labels= sets what to put at each tick. If absent (like it is above), it just prints the at value.
    • las=2 rotates the number so that it is perpendicular to the axis line. I did this to show more of the numbers, otherwise they will mask a bit more.

    While this shows every-other, that is affected by the size of the canvas; if you do the same plot in full-screen, it'll show every number.