简体   繁体   中英

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

在此处输入图片说明

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

在此处输入图片说明

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 在此处输入图片说明

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM