Fixing R Error Message: error in plot.window(…) : need finite ‘ylim’ values

While error messages are a nuisance to programmers they do tell you when there is a problem. Unfortunately, they are not always helpful at telling you what the problem is but in most cases the better you understand the error the more sense it makes. The “error in plot.window(…) : need finite ‘ylim’ values” error message is just such an error message.

The circumstances of this error

This error message occurs when you are using the plot() function and there is at least one complete column of “NA” values. This is the key to understanding this error message and how it works.

> df = read.table(text = ‘
+ A B C D
+ 1 3 20 81 NA
+ 2 4 34 13 NA
+ 3 5 46 18 NA
+ 4 6 42 16 NA
+ 5 7 65 26 NA’, header=TRUE)
>
> plot(df, main = ‘test plot’)
Error in plot.window(…) : need finite ‘ylim’ values
In addition: Warning messages:

In this sample code column “D” has nothing but “NA” values. Consequently, it has no value from the column to use in the graph. As a result, it produces our error message

What is causing this error?

This error results from the fact that when graphing a data frame the plot() function is looking for numeric values. The plot() function graph data frame based on the columns and so, it returned an error message if there are only “NA” values in any column.

> df = read.table(text = ‘
+ A B C D
+ 1 NA NA NA NA
+ 2 4 34 13 22
+ 3 5 46 18 23
+ 4 6 42 16 24
+ 5 7 65 26 25′, header=TRUE)
>
> plot(df, main = ‘test plot’)

The fact that it is columns and not rows that caused this error message is illustrated by the above example. Here, there is a row of all “NA” values but every column has some numeric values and this code runs fine.

How to fix this error

Fixing this error is a simple matter of getting rid of all of the “NA” values in one row of the data frame.

> df = read.table(text = ‘
+ A B C D
+ 1 3 42 NA NA
+ 2 4 34 NA 22
+ 3 5 46 NA 23
+ 4 NA NA NA NA
+ 5 7 NA NA 25′, header=TRUE)
> for(y in 1:ncol(df)){
+ if (is.na(df[1,y])) df[1,y] = 0
+ }
> plot(df, main = ‘test plot’)

In this example, all of the “NA” values in the first row are zeroed out using a for-loop. This process ensures that at least one row in each column has a numeric value. This process prevents the error from occurring.