2

I'm working on a population pyramide that should be saved as a gif. Kind of like in this tutorial of Flowing Data, but with ggplot instead of plotrix.

My workflow:

1) Create a population pyramide

2) Create multiple pyramide-plots in a for-loop

for (i in unique(d$jahr)) {

  d_jahr <- d %>%
    filter(jahr == i)

  p <- ggplot(data = d_jahr, aes(x = anzahl, y = value, fill = art)) +
    geom_bar(data = filter(d_jahr, art == "w"), stat = "identity") +
    geom_bar(data = filter(d_jahr, art == "m"), stat = "identity") +
    coord_flip() +
    labs(title = paste(i), x = NULL, y = NULL)

  ggsave(p,filename=paste("img/",i,".png",sep=""))

}

3) Save the plots as gif with the animation package

My problem:

All years have different values, so the x-axis have different ranges. This results in weird looks in a gif, because the center of the plots jumps to the right, to the left, to the right...

Is it possible to fix the x-axis (in this case y-axis, because of coord-flip()) over multiple plots that are created independently?

kabr
  • 1,249
  • 1
  • 12
  • 22
  • [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) – zx8754 Apr 11 '16 at 08:00
  • 1
    Maybe this package: https://github.com/dgrtwo/gganimate – zx8754 Apr 11 '16 at 08:01
  • Please read [how do I ask a good question](http://stackoverflow.com/help/how-to-ask) and [proding a minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610) and edit your post accordingly. I.e., provide input data (dummy or real) and reduce the code to the lines that are part of the problem (e.g. prob is ggplot, not saving a jpeg). – lukeA Apr 11 '16 at 08:04
  • @zx8754 gganimate seems like a good idea, thanks – kabr Apr 11 '16 at 08:30

1 Answers1

4

You can fix the range of an axis by setting the limits parameter:

library(ggplot2)
lst <- list(
  data.frame(x = 1:100, y=runif(100, 0, 10)),
  data.frame(x = 1:100, y=runif(100, 0, 100))
)
ylim <- range(do.call(c, lapply(lst, "[[", "y")))
for (x in seq(lst)) {
  print(ggplot(lst[[x]], aes(x, y)) + geom_point() + scale_y_continuous(limits=ylim))
}

or by adding +ylim(ylim) instead of +scale_y_continuous(limits=ylim) (via @DeveauP).

lukeA
  • 53,097
  • 5
  • 97
  • 100