r-将图例中未使用的因子保留在drop=FALSE无效



我正在使用ggplot2进行一系列绘图,然后我想将这些绘图拼凑成gif。为了做到这一点,我需要每个情节的传说都是一样的。我以前通过设置drop=FALSE来完成此操作。然而,这一次图例仍然在删除未使用的级别。我在循环中进行了检查,col.scale$drop、col.scale$调用、col.scal$name和q$scale似乎都返回drop=FALSE。有什么建议可以避免在这里丢弃未使用的级别吗?

library(ggplot2);library("animation")
# animiation makes it easier to see the problem, but is not necessary.
row1 <- cbind("2013-01-01 05:58:00", "41.8713", "-1.268867", "Tag1")
row2 <- cbind("2013-01-01 17:58:00",  "41.8707", "-1.267400", "Tag1")
row3 <- cbind("2013-01-01 23:58:00", "41.8707", "-1.267400", "Tag1")
row4 <- cbind("2013-01-02 05:58:00", "41.8707", "-1.267400", "Tag1")
row5 <- cbind("2013-01-01 11:58:00", "47.5513", "-1.922600",  "Tag2")
row6 <- cbind("2013-01-01 17:58:00", "48.6780", "-1.986267",  "Tag2")
all.birds <- as.data.frame(rbind(row1, row2, row3, row4, row5, row6))
names(all.birds) <- c("time", "x",   "y",   "bird")
all.birds$time <- as.POSIXlt(as.character(all.birds$time))
all.birds$x <- as.numeric(as.character(all.birds$x))
all.birds$y <- as.numeric(as.character(all.birds$y))
all.birds$bird <- as.character(all.birds$bird)
bird.time <-sort(unique(all.birds$time))
time.events<-length(bird.time)
my.colours <- c("#FF0000", "#00FF00")
col.scale <- scale_colour_manual(name = "birds",values = my.colours, drop=FALSE)
make.one.chart <- function(all.birds, bird.time, col.scale, i, q){
  x<-subset(all.birds, time==bird.time[i])
  p<-q+geom_point(data=x, aes(x, y, colour=bird), size=5)
  p <- p+coord_cartesian(xlim = c(30, 70), ylim= c(-2.4,-1.0))
  filename <- paste("file",i,".png", sep="")
  png(file=filename, width = 1024, height = 768)
  print(p)
  dummy <- dev.off()
}
q<-ggplot() + col.scale
i<-1
step<-1
while (i <= time.events){
  make.one.chart(all.birds, bird.time, col.scale, i, q)
  print(i)
  i<-i+step
}
# You will now have five files, for example, file1.png. Open these to see the charts
# If you use the animation package, the following lines will work....
files = sprintf('file%d.png', seq(from=1, to=time.events, by=step))
im.convert(files, output = 'Three Panel View.gif')

当然会删除"级别"。你没有一个因子,直到你把它传递给ggplot,迫使它为一。。。相反,在调用函数之前,请显式地将birds设为一个因子。

all.birds$birds <- factor(all.birds$birds)

然后运行循环。如果我误解了,请澄清。

最新更新