How to fix: error in xy.coords(x, y, xlabel, ylabel, log) : ‘x’ and ‘y’ lengths differ

This error occurs when the lengths of the x and y values used in the xy.coords function are not the same. To fix this error, ensure that both the x and y values have the same length, or remove some of the values from either the x or y values to make them the same length. If the x and y values are to be used in a logarithmic scale, the same number of values must be used for both x and y.


One common error you may encounter in R is:

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ 

This error occurs when you attempt to create a plot of two variables but the variables don’t have the same length.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we attempt to create a scatterplot of the following two variables in R:

#define x and y variables
x <- c(2, 5, 5, 8)
y <- c(22, 28, 32, 35, 40, 41)

#attempt to create scatterplot of x vs. y
plot(x, y)

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ

We receive an error because the length of x and y are not equal.

We can confirm this by printing the length of each variable:

#print length of x
length(x)

[1] 4

#print length of y
length(y)

[1] 6

#check if length of x and y are equal
length(x) == length(y)

[1] FALSE

How to Fix the Error

The easiest way to fix this error is to simply make sure that both vectors have the same length:

#define x and y variables to have same length
x <- c(2, 5, 5, 8, 9, 12)
y <- c(22, 28, 32, 35, 40, 41)

#confirm that x and y are the same length
length(x) == length(y)

[1] TRUE

create scatterplot of x vs. y
plot(x, y)

If one vector happens to be shorter than the other, you could choose to plot only the values up to the length of the shorter vector.

For example, if vector x has 4 values and vector y has 6 values, we could create a scatterplot using only the first 4 values of each vector:

#define x and y variables
x <- c(2, 5, 5, 8)
y <- c(22, 28, 32, 35, 40, 41)

#create scatterplot of first 4 pairwise values of x vs. y
plot(x, y[1:length(x)])

Notice that only the first four values of each vector are used to create the scatterplot.

x