Suppose I have created a simple plot like this:
xvalues <- 100:200
yvalues <- 250:350
plot(xvalues, yvalues)
However, I would like the x-axis to start at 0 and leave the upper bound to be whatever is computed by R. How can I do this?
I know there is an option for xlim=c(lower bound, upper bound), but I don't know what the upper bound is. Also, I am evidently unable to let the upper bound be unspecified:
> plot(xvalues, yvalues, xlim=c(0))
Error in plot.window(...) : invalid 'xlim' value
It would be great if I didn't have to compute the max value of the xvalues vector in order to get the upper bound, as that seems wasteful for a very large data vector.
To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.
The xlim() function with the provided parameters as the range of the x-axis in vectors is used to set the x-axis without dropping any data of the given plot or an object accordingly. Parameters: …: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
xlim: Set or query x-axis limits. ylim: Set or query y-axis limits.
ylim( limits ) sets the y-axis limits for the current axes or chart. Specify limits as a two-element vector of the form [ymin ymax] , where ymax is greater than ymin . example.
You could use one of two approaches:
Calculating the limits
xlim <- c(0, max(xvalues))
xlim
can now be supplied as the xlim
argument in plot
.
xvalues <- 100:200
yvalues <- 250:350
plot(xvalues, yvalues, xlim=xlim)
Let par
return the limits
This one is a bit more sophisticated, but sometimes helpful (certainly overkill in your case, but for completeness). You plot the data once, you get the limits of the plotting area in user coordinates using par("usr")
. Now you can use these in your new plot.
plot(xvalues, yvalues, xaxs="i")
xmax <- par("usr")[2]
plot(xvalues, yvalues, xlim=c(0,xmax))
PS. I used xaxs="i"
so the results will be without small extensions at the ends.
you can simply set the max for x
using the max of you values:
xvalues <- 1:99
yvalues <- rep(1,99)
plot(xvalues, yvalues, xlim = c(0, max(xvalues)) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With