Homunculus Reticulli
Homunculus Reticulli

Reputation: 68406

Sensible choice values for ylim parameter in plot() function

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

Upvotes: 1

Views: 5803

Answers (1)

Michael
Michael

Reputation: 5898

Try restricting your dataset (or at least your calls to find a plotting range) to finite and non-missing values prior to plotting.

> plot(1:2,1:2, ylim=c(NA,3))
Error in plot.window(...) : need finite 'ylim' values
> plot(1:2,1:2, ylim=c(-Inf,3))
Error in plot.window(...) : need finite 'ylim' values

?is.na ?is.finite

> min(c(NA,3,5))
[1] NA
> min(c(NA,3,5),na.rm=TRUE)
[1] 3
> min(c(-Inf,3,5),na.rm=TRUE)
[1] -Inf
> 
> y <- c(-Inf,NA,3,4,5)
> range(y)
[1] NA NA
> range(y, na.rm=TRUE)
[1] -Inf    5
> range(y[!is.na(y) & is.finite(y)])
[1] 3 5
> 

Upvotes: 1

Related Questions