Boxplot and xyplot overlapped

2.2k Views Asked by At

I've done a conditional boxplot with my data, with the bwplot function of the lattice library.

    A1 <- bwplot(measure ~ month | plot , data = prueba,
              strip = strip.custom(bg = 'white'),   
              cex = .8, layout = c(2, 2),
              xlab = "Month", ylab = "Total",
              par.settings = list(
                box.rectangle = list(col = 1),
                box.umbrella  = list(col = 1),
                plot.symbol   = list(cex = .8, col = 1)),
              scales = list(x = list(relation = "same"),
                            y = list(relation = "same")))

Then, I've done a xyplot because I want to add the precipitation data to the previous graph, using xyplot from lattice library also.

    B1 <- xyplot(precip ~ month | plot, data=prueba,
   type="b",
   ylab = '% precip',
   xlab = 'month',
   strip = function(bg = 'white', ...)
     strip.default(bg = 'white', ...),
   scales = list(alternating = F,
                 x=list(relation = 'same'),
                 y=list(relation = 'same')))

I've try to draw them on the same graph using grid.arrange from gridExtra library:

    grid.arrange(A1,B1)

But with this, I don't overlap the data, but the result is this boxplot and xyplot

How could I draw the precipitacion data "inside" the boxplots conditioned by plot?

Thank you

2

There are 2 best solutions below

6
AudioBubble On BEST ANSWER

Using the barley data as Andrie did, another approach with latticeExtra:

library(lattice)
library(latticeExtra)

bwplot(yield ~ year | variety , data = barley, fill = "grey") +
xyplot(yield ~ year | variety , data = barley, col = "red")

enter image description here

1
Andrie On

You need to create a custom panel function. I demonstrate with the built-in barley data:

Imagine you want to create a simple bwplot and xyplot using the barley data. Your code might look like this:

library(lattice)

bwplot(yield ~ year | variety , data = barley)
xyplot(yield ~ year | variety , data = barley)

To combine the plots, you need to create a panel function that first plots the default panel.bwplot and then the panel.xyplot. Try this:

bwplot(yield ~ year | variety , data = barley,
       panel = function(x, y, ...){
         panel.bwplot(x, y, fill="grey", ...)
         panel.xyplot(x, y, col="red", ...)
       }
)

enter image description here


There is some information about doing this in the help for ?xyplot - scroll down to the details of the panel argument.