I have an R script that plots data from a file. The script currently uses hard coded values for ylim. I want to dynamically determine the correct (i.e. sensible) values for ylim, based on the data being plotted.
I am restricting the x axis values using xlim
. I would have thought that the plot function will then be able to work out the y values (based on the x axis values selected by xlim
) - without me having to provide ylim arguments, however, when I called plot(), with xlim
but no ylim
argument, I got the following error:
Error in plot.window(...) : need finite 'ylim' values
Calls: plot -> plot.default -> localWindow -> plot.window
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
So my question, is, how do I dynamically determine the values to specify for ylim
, given that I have specified limits for xlim
?. Ideally, I would like to specify ylim
limits as follows:
ylim_lower <- (y value for xlim_lower) - [some fixed % distance]
ylim_upper <- (y value for xlim_upper) + [some fixed % distance]
How can I to do this?
[[Edit]]
dat <- read.csv(somefile)
n <- dim(dat)[1]
yvals1 <- rep(0,n)
yvals2 <- rep(0,n)
for(i in 1:n){
yvals1[i] <- foobar1(dat$X[i])
yvals2[i] <- foobar2(dat$X[i])
}
# Note: yvals1 and yvals2 MAY contain NAs
# below is the plot command that barfs:
plot(dat$X, yvals1, typ="l", col="green", xlim=c(lowest_val_cuttoff, highest_val_cuttoff), ylim= c(.2, .60), main=c(the_title, "Title goes here"), xlab="x axis label", ylab="y axis label")
lines(dat$X, yvals2, col="red")