我正在用ggplot2做一系列的情节,然后我想把它拼成一个gif。为了实现这一点,我需要每个情节的图例都相同。我之前通过设置drop = FALSE完成了这个。但是这次传说仍然没有丢失未使用的级别。我在循环中检查过,col.scale $ drop,col.scale $ call,col.scale $ name和q $ scales all似乎都返回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')
答案 0 :(得分:1)
当然“水平”会被取消。在将其强制转换为ggplot
并将其强制转换为一个因素之前,您没有因素...相反,在调用函数之前,明确地将birds
作为一个因素。
all.birds$birds <- factor(all.birds$birds)
然后运行你的循环。如果我误解了,请澄清。