2

I have a data frame with observations each month. I would like to create a gif of the observations each month. However, in gganimate, the frames are ordered alphabetically (e.g. starting with April instead of January). How can I change the order of the frames?

Alternatively, I could use the number of the month to get the plot to run correctly. However, in that case I would have to change the frame title to January, February, March etc. instead of 1, 2, 3 ... I realize that this response could solve the problem, but it still doesn't answer whether or not it's possible to somehow dictate the order of frames in gganimate.

monthly.data <- data.frame(month = rep(c("January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November", "December"), 10), xval = rnorm(n = 120,10,3), yval=rnorm(120,10,3))

    # This plots it in alphabetical order
    ggplot(monthly.data, aes(x = xval, y = yval))+
      geom_point()+
      transition_states(month)+
      ggtitle("{closest_state}")

    # Ordering the dataframe correctly doesn't help
    mothly.data <- arrange(monthly.data, factor(month, levels = c("January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November", "December")))

    ggplot(monthly.data, aes(x = xval, y = yval))+
      geom_point()+
      transition_states(month)+
      ggtitle("{closest_state}")
Alex Krohn
  • 71
  • 5
  • 1
    `monthly.data$month = factor(monthly.data$month, levels = month.name)`, using the built-in `month.name` vector that has the months in the right order. Order of rows doesn't matter. Order of factor levels matters. – Gregor Thomas Mar 11 '20 at 20:39

1 Answers1

3

ggplot cares about the orders of the levels of factors when plotting.

You can create months vector as a factor with desired levels from start, it is up to you.

Edit: Referring to @Gregor Thomas' comment

monthly.data$month = factor(monthly.data$month, levels = month.name)

eonurk
  • 507
  • 2
  • 12
  • 1
    `relevel` seems like a bad way to do this... why one level at a time? – Gregor Thomas Mar 11 '20 at 20:42
  • yeah, it is better to define it as a `factor` in the start. There are other libraries that does releveling in batch of course, but relevel just takes one argument at a time as far as I know. – eonurk Mar 11 '20 at 20:44
  • exactly, the way you did it lol. `monthly.data$month = factor(monthly.data$month, levels = month.name)` – eonurk Mar 11 '20 at 20:48
  • Right, `relevel` is for making a level the first level. If you want to change all the levels, you would just use `factor` again. Just because you didn't specify the levels all at once the first time doesn't mean you can't do it now. – Gregor Thomas Mar 11 '20 at 20:48
  • @eonurk Thanks! This worked perfectly. I thought I changed it to a factor in the arrange() command, but I see now that I just ordered a character vector by a list of factors. Rookie mistake. – Alex Krohn Mar 13 '20 at 15:47