Search code examples
rplotgraphicslattice

Set color segments by group


I am trying to made a kind of xyplot with a line from the bottom till the value. The problem is that I don't know how to adjust the color of the line.

time <-  rnorm(50, 5, 2)
death.count <- rnorm(50, -0.25, 0.25)
Inoc.size <-rep(c("A", "B"), times=25)
    
data <- data.frame(time, death.count, Inoc.size)   
    
xyplot(death.count ~ time, data,
       groups=Inoc.size, ylim=c(0, -0.5),
       xlab=list("Time - h", cex=1.5),
       ylab=list(expression("Death cells - ln N"[i]), cex=1.5),
       par.settings=list(
           alpha=0.5,
           superpose.symbol=list(pch=c(15, 16, 17, 18), 
               col=c(myColours[3], myColours[6], myColours[4], myColours[7]))),
           auto.key=T,
           panel=panel.superpose,
           panel.groups=function(x, y, col, group.number, groups, ...) {
               xj <- jitter(as.numeric(x), factor=0.5)
               panel.xyplot(xj, y, ...)
               panel.segments(x0=xj, x1=xj, y0=0, y1=y, groups, lwd=2)
           }
)

This is what I see now, I would like to see each bar with a different color


Solution

  • I don't quite see how your plot matches with your code. But this may work for you. Define col within panel.groups and reference that indexed by group.number in panel.segments.

    library(lattice)
     myColours=1:7
     time<-  rnorm(50,5,2)
         death.count<- rnorm(50,-0.25,0.25)
         Inoc.size<-rep(c("A","B"),times=25)
    
         data<-data.frame( time,death.count, Inoc.size)  
    
     xyplot(death.count~time, data,
           groups=Inoc.size,#ylim=c(0,-0.5),
        xlab = list("Time - h", cex=1.5),
       ylab = list(expression("Death cells - ln N"[i]), cex=1.5),
        par.settings= list(
         alpha = 0.5,superpose.symbol=list(
         pch=c(15,16,17,18),
          col=c(myColours[3],myColours[6],myColours[4],myColours[7])),
             pch=c(15,16,17,18),
         col=c(myColours[3],myColours[6],myColours[4],myColours[7])),
           auto.key=T,
        panel = panel.superpose,
            panel.groups = function(x, y, col,group.number,groups, ...) {
               xj=jitter(as.numeric(x), factor=0.5)
     col=c(myColours[3],myColours[6],myColours[4],myColours[7])
               panel.xyplot(xj,y,...)
               panel.segments(x0=xj,x1=xj, y0=0, y1=y,col=col[group.number],groups,
                                            lwd = 2)
                                  }
                         )