Reputation: 2155
I am doing a series of plots with ggplot2, which I then want to piece together into a gif. For this to work, I need the legend to be the same for each plot. I have done this before by setting drop=FALSE. However this time the legend is still dropping unused levels. I've checked within the loop, and col.scale$drop, col.scale$call, col.scale$name, and q$scales all seem to return drop=FALSE. Any suggestions on what I can to to avoid dropping unused levels here?
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')
Upvotes: 2
Views: 2271
Reputation: 43255
Of course the "levels" are dropped. You don't have a factor until you pass it to ggplot
that coerces it to one... Instead, explicitly make birds
a factor before you call the function.
all.birds$birds <- factor(all.birds$birds)
Then run your loop. If I've misunderstood, please clarify.
Upvotes: 1