Arne Arne - 3 months ago 46
R Question

Adding abline of different data to xyplot panels

Using lattice in R, I have plotted an xyplot using the factors option. Now I want to add a horizontal abline to every plot, however out of another dataframe. How can I get these lines in their correspondent panel?

EDIT - example:

MyData <- data.frame(
v1 = 1:50,
v2 = rnorm(50,20,5),
v3 = c(rep("one", 10), rep("two", 10), rep("three", 10), rep("four", 10), rep("five", 10)))


require(latticeExtra)

xyplot(
v1 ~ v2 | v3,
data = MyData,
layout = c(5, 1),
scales = list(
x = list(relation="free"),
y = list(relation="same")
)
)

# Now the horizontal lines I want to draw
lineData <- c(30,30,20,20,40)
# each for one column, from left to right; another option would be
lineData <- data.frame(
v3 = c("one","two","three","four","five"),
height = c(30,30,20,20,40)
)

# I know this will not work for each correspondent panel, separately...
abline(h = lineData)

Answer

Here's how i'd do it to make sure the values match up

lineData <- data.frame(
  v3 = c("one","two","three","four","five"),
  height = c(30,30,20,20,40)
)

xyplot(
  v1 ~ v2 | v3,
  data = MyData,
  layout = c(5, 1),
  scales = list(
    x = list(relation="free"),
    y = list(relation="same")
  ),
  panel = function(x, ...) {
      level <- dimnames(trellis.last.object())[["v3"]][packet.number()]
      panel.xyplot(x, ...);
      panel.abline(h = lineData$height[lineData$v3==level])
  }
)

This produces

enter image description here

Comments