Alex Krohn
Alex Krohn

Reputation: 123

How to un-alphabetize frame order in gganimate?

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}")

Upvotes: 2

Views: 240

Answers (1)

eonurk
eonurk

Reputation: 547

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)

Upvotes: 3

Related Questions