How to Fix: Error in plot.window(…) : need finite ‘xlim’ values


One error you may encounter when using R is:

Error in plot.window(...) : need finite 'xlim' values

This error occurs when you attempt to create a plot in R and use either a character vector or a vector with only NA values on the x-axis.

The following examples show two different scenarios where this error may occur in practice.

Example 1: Error with Character Vector

Suppose attempt to create a scatterplot using the following code:

#define data
x <- c('A', 'B', 'C', 'D', 'E', 'F')
y <- c(3, 6, 7, 8, 14, 19)

#attempt to create scatterplot
plot(x, y)

Error in plot.window(...) : need finite 'xlim' values

We receive an error because the vector that we used for the x-axis values is a character vector.

To fix this error, we simply need to supply a numeric vector to the x-axis:

#define two numeric vectors
x <- c(1, 2, 3, 4, 5, 6)
y <- c(3, 6, 7, 8, 14, 19)

#create scatterplot
plot(x, y)

We’re able to create the scatterplot without any errors because we supplied a numeric vector for the x-axis.

Example 2: Error with Vector of NA Values

Suppose attempt to create a scatterplot using the following code:

#define data
x <- c(NA, NA, NA, NA, NA, NA)
y <- c(3, 6, 7, 8, 14, 19)

#attempt to create scatterplot
plot(x, y)

Error in plot.window(...) : need finite 'xlim' values

We receive an error because the vector that we used for the x-axis values is a vector with only NA values.

To fix this error, we simply need to supply a numeric vector to the x-axis:

#define two numeric vectors
x <- c(1, 5, 9, 13, 19, 22)
y <- c(3, 6, 7, 8, 14, 19)

#create scatterplot
plot(x, y)

Once again we’re able to successfully create a scatterplot with no errors because we used a numeric vector for the x-axis.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix R Error: Unexpected String Constant
How to Fix R Error: Discrete value supplied to continuous scale
How to Fix R Error: argument is not numeric or logical: returning na

Leave a Reply

Your email address will not be published. Required fields are marked *