0

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?

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293
  • You can include `axes=FALSE'` in the initial call to `plot()` and then use `axis()` to build custom axes with the ticks and labels where you like using 'at', e.g., at=seq(0, 2, 0.5) for your axis. – ulfelder Jul 14 '15 at 09:53
  • 2
    As a side note: Always set a seed before generating random numbers (e.g. `set.seed(1)`) so others can fully reproduce your output. – lukeA Jul 14 '15 at 09:58
  • @lukeA thanks, I will try to improve in the future. – René Nyffenegger Jul 14 '15 at 11:16

1 Answers1

0

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?

ulfelder
  • 5,305
  • 1
  • 22
  • 40