1

我正在使用 ggplot2 进行一系列绘图,然后我想将它们拼凑成一个 gif。为此,我需要每个情节的图例都相同。我之前通过设置 drop=FALSE 来做到这一点。然而,这一次传说仍在下降未使用的水平。我在循环中检查过,col.scale$drop、col.scale$call、col.scale$name 和 q$scales 似乎都返回 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')
4

1 回答 1

1

当然,“水平”会下降。在将其传递给将ggplot其强制为一个之前,您没有因子...相反,birds在调用该函数之前显式地创建一个因子。

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

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

于 2013-08-04T01:15:18.113 回答