How can I get alternating colors of the box rectangles in lattice bwplot?

504 Views Asked by At

When I execute the following code (datasets are part of lattice package):

ngroups <- length(unique(barley$site)) + 1

bwplot(yield ~ variety, data = barley, box.width = 1/ ngroups,
       groups = year, scales=(x=list(rot=45)), 
       auto.key = list(points = FALSE, rectangles = TRUE, space = "right"),
       par.settings=list(box.rectangle = list(col=c("red", "green"), lwd=3),
                         superpose.polygon=list(col=c("green", "red"), pch=c(15,15))
                         ),
       panel.groups = function(x, y, ..., group.number) {
         panel.bwplot(x + (group.number-1.5)/ngroups, y, ...)
       },
       panel=function(...) {
         panel.grid(h = -1, v=0)
         panel.superpose(par.settings=list(box.rectangle=list(col=c("green", "red"))),  ...)
       }
      ) 

I get the following graph:

enter image description here

How can I get alternating colors of red and green for the boxes from left to right? (I noticed that if I delete the custom panel it works well, but I want to keep the grey reference lines.)

Thanks.

1

There are 1 best solutions below

1
Johan Larsson On

I have a solution for you if you're willing to use fill instead of borders to distinguish between the years. I also switched the order of the colors in one place where it seemed to be wrong(?), and dropped some redundant code.

bwplot(yield ~ variety, data = barley, box.width = 1 / ngroups,
       groups = year, scales = (x = list(rot = 45)),
       par.settings = list(superpose.polygon = list(col = c("green", "red"),
                                                    pch =c (15, 15)),
                         superpose.symbol = list(fill = c("green", "red"))),
       auto.key = list(points = FALSE, rectangles = TRUE, space = "right"),
       panel.groups = function(x, y, ..., group.number) {
         panel.bwplot(x + (group.number - 1.5) / ngroups, y, ...)
       },
       panel = function(...) {
         panel.grid(h = -1, v = 0)
         panel.superpose(...)
       }
) 

enter image description here