Search code examples
rgraphscalelatticeaxis-labels

Lattice: Plotting two lines with different scale and axes in the same panel


I have something like this:

a <- c(1,4,2,8)
b <- c(100,80,40, 0)
c <- 1:4
x <- rep("foo",4)
y <- rep("bar",4)

df1 <- data.frame(c, y = a, gr = x)
df2 <- data.frame(c, y = b, gr = y)
df <- rbind(df1,df2)

xyplot(y ~ c, data = df, type = "l", group = df$gr)

Results in this:

enter image description here

I am looking for a way that would allow me to change the scale so that the blue line fills the entire panel area, and add a corresponding axis to the right side of the plot.

If adding the axis is too hard, then it is not a requirement. The units on the y axis are arbitrary anyway (in my own data). Maybe a way to normalize the data would work?

There are several answers on this site, but they all work on the basic graphics of R, and none using lattice.


Solution

  • Is it what you want?

    library(latticeExtra)
    library(dplyr)
    dfgr <-df %>% filter(gr == "foo")
    dfbar <-df %>% filter(gr == "bar")
    obj1 <- xyplot(y ~ c, dfgr, type = "l")
    obj2 <- xyplot(y ~ c, dfbar, type = "l")
    doubleYScale(obj1, obj2, add.ylab2 = TRUE)
    

    enter image description here