Search code examples
rlatticelmplot

How to write the conditional branches for R lattice package


I use lattice package to draw the picture using the below csv file.

csv file

I used the below code and got the expected picture.

library(lattice)

data_1 <- read.table("./stackoverflow.csv", header=T, sep=",")
data <- na.omit(data_1)

xyplot(a ~ b | c, data = data, panel = function(x, y){
  panel.xyplot(x, y)
}
)

enter image description here

Moreover, I used the below code and got the next expected picture.

library(lattice)

data_1 <- read.table("./stackoverflow.csv", header=T, sep=",")
data <- na.omit(data_1)

xyplot(a ~ b | c, data = data, panel = function(x, y){
  panel.xyplot(x, y)
panel.lmline(x, y)
}
)

enter image description here

I want not to use panel.lmline for the data leading to the error message, and I want the below picture. The picture is the composite (damy) image.

enter image description here

How should I do to use the conditional branches for R lattice package.

R 4.0.5, lattice 0.20-38, MacOS 10.14.5 were used.


Solution

  • The error is caused because all the values on the x-axis for that panel are the same so it's not possible to calculate a line. You can check for a non-zero range and only draw the line when possible using the following code

    xyplot(a ~ b | c, data = data, panel = function(x, y){
      panel.xyplot(x, y)
      if(diff(range(x)) > 0) {
        panel.lmline(x, y)
      }
    })