Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting R plot xlim with only the lower bound

Tags:

r

Suppose I have created a simple plot like this:

xvalues <- 100:200
yvalues <- 250:350
plot(xvalues, yvalues)

enter image description here

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.

like image 622
stackoverflowuser2010 Avatar asked Jan 18 '14 18:01

stackoverflowuser2010


People also ask

How do I limit the y axis in R?

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.

How do I write an XLIM in R?

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.

Which function used for setting axis limits in any graph in R?

xlim: Set or query x-axis limits. ylim: Set or query y-axis limits.

What does YLIM mean in Rstudio?

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.


2 Answers

You could use one of two approaches:

Calculating the limits

xlim <- c(0, max(xvalues))

xlim can now be supplied as the xlimargument in plot.

xvalues <- 100:200
yvalues <- 250:350
plot(xvalues, yvalues, xlim=xlim)

enter image description here

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.

like image 164
Mark Heckmann Avatar answered Oct 16 '22 19:10

Mark Heckmann


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)) )

enter image description here

like image 37
user1317221_G Avatar answered Oct 16 '22 20:10

user1317221_G