Search code examples
rplotlabelaxis-labels

How can I have the full range in the x- and y-axis labels in a plot?


I have two variables, x and y

x = runif(8, 0, runif(1, 1, 5))
y = x^2

that I want to plot. Note that the range of x (and hence y=x^2) is not always the same.

So, the command

plot(x, y, pch=19, col='red')

produces

enter image description here

However, I don't want the borders around the graph, so I use the bty='n' parameter for plot:

plot(x, y, pch=19, col='red', bty='n')

which produces

enter image description here

This is a bit unfortunate, imho, since I'd like the y-axis to go all the way up to 4 and the x-axis all the way to 2.

So, I ue the xaxp and yaxp parameters in the plot command:

plot(x, y, pch=19, col='red', bty='n', 
     xaxp=c(
       floor  (min(x)),
       ceiling(max(x)),
       5
    ),
    yaxp=c(
       floor  (min(y)),
       ceiling(max(y)),
       5
    )
)

which produces enter image description here

This is a bit better, but it still doesn't show the full range. Also, I thought it nice that the default axis labaling uses steps that were like 1,2,3,4 or 0.5,1,1.5,2, not just some arbitrary fractions.

I guess R has some parameter or mechanism to plot the full range in the axis in a "humanly" fashion (0.5,1,1.5 ...) but I didn't find it. So, what could I try?


Solution

  • Try:

    plot(x, y, pch=19, col='red', bty='n', xlim=c(min(x),max(x)),
      ylim=c(min(y),max(y)), axes=FALSE)
    axis(1, at=seq(floor(min(x)), ceiling(max(x)), 0.5))
    axis(2, at=seq(floor(min(y)), ceiling(max(y)), 0.5))
    

    Or if you'd prefer to hard-code those axis ranges:

    axis(1, at=seq(0, 2, 0.5))
    axis(2, at=seq(0, 4, 0.5))
    

    Is that what you were after?