문제

Hi I am trying to add a mean line to a lattice xyplot using the following code... which doesn't work...

library(lattice)
temp <- data.frame(c(1,1,1,1,1,1,2,2),
      c(1,1,2,2,1,1,1,1),
      c(1,1,1,2,1,2,1,2),
      c(0,0,0,150,150,0,0,0),
      c(3,10,4,15,14,2,4,5))
names(temp) <- c("instNo","NoOfAC","NoReleaseLevels","trExt","maxDelay")

tempavg <- aggregate(temp[5], by=list(temp$NoOfAC,temp$NoReleaseLevels
                                  ,temp$trExt),FUN = mean)

names(tempavg) <- c("NoOfAC","NoReleaseLevels","trExt","meanDelay")
xyplot(maxDelay ~ NoOfAC |trExt + NoReleaseLevels,
             data = temp,
             panel = function(x, y, tempavg) {
               panel.xyplot(x, y)
               panel.abline(tempavg$meanDelay ~ y |trExt + NoReleaseLevels)
             },
xlab = "Number Of Aircraft in the Instance",
ylab = "Total Delay (minutes)")
도움이 되었습니까?

해결책

The main issue with your approach is where does it say that panel.abline() takes a formula as its first argument? (It doesn't!) What ?panel.abline says is that it takes arguments h and v (in particular for the case you have in mind) and you want argument h.

Note also that lattice calls the panel functions with arguments x and y containing the x and y data for each panel drawn. You don't need to do the subsetting and aggregating externally for this work; it is done for you. Hence you need to think in terms of x and y when drawing with panel functions.

In this case, you want panel.abline(h = mean(y), ...) in your panel function. The ... is there to allow extra arguments passed to the panel function to propagate down to the function calls within the panel function. Hence your anonymous panel function also needs to take a ... argument. This is shown below.

## code as factor
temp <- transform(temp, NoOfAC = factor(NoOfAC))

## plot
xyplot(maxDelay ~ NoOfAC |trExt + NoReleaseLevels,
             data = temp,
             panel = function(x, y, ...) {
               panel.xyplot(x, y, ...)
               panel.linejoin(x, y, horizontal = FALSE, ...)
             },
       xlab = "Number Of Aircraft in the Instance",
       ylab = "Total Delay (minutes)")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top