5

I've been playing with the waffle package, and am trying to get it to work with gganimate.

Using mpg as an example, I've created waffle charts to show number of models by each class. I would then like to use gganimate to display, in turn, a chart of models by class for each manufacturer. I can use facet_wrap() to show charts for all manufacturers at once, but would like to be able to cycle through them.

When I try to apply gganimate to a waffle plot, I get the error:

Error in mapply(FUN = f, ..., SIMPLIFY = FALSE) : zero-length inputs cannot be mixed with those of non-zero length

I'm not sure if waffle is incompatible with gganimate, or if I'm doing something wrong.

Here's the code:

library(tidyverse)
library(waffle)
library(gganimate)

data("mpg")
d <- mpg

d$class <- as.factor(d$class)
d$manufacturer <- as.factor(d$manufacturer)

plot <- d %>% count(manufacturer, class) %>%
  ggplot(aes(fill = class, values = n)) +
  geom_waffle(color = "white",
              size = .75,
              n_rows = 4) +
  ggthemes::scale_fill_tableau(name = NULL) +
  coord_equal() +
  theme_minimal() +
  theme(panel.grid = element_blank(), axis.text = element_blank(), legend.position = "bottom")

#Facet wrap works fine:
plot + facet_wrap(~ manufacturer)

#gganimate returns error:
plot + transition_states(manufacturer, transition_length = 2, state_length = 2)


Would really appreciate any help! Thanks.

Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36
jllls
  • 83
  • 4

1 Answers1

4

I'm not sure about the compatibility of ggwaffle with gganimate, but another option is to use the animation package to create a GIF. For example:

library(animation)

saveGIF({
  for (i in unique(d$manufacturer)) {

    d1 = d %>% filter(manufacturer==i)

    gg1 <- d1 %>%
      count(manufacturer, class) %>%
      ggplot(aes(fill = class, values = n)) +
        geom_waffle(color = "white",
                    size = .75,
                    n_rows = 4) +
        scale_y_continuous(expand=c(0,0)) +
        ggthemes::scale_fill_tableau(name = NULL) +
        coord_equal() +
        theme_minimal(base_size=40) +
        theme(panel.grid = element_blank(), 
              axis.text = element_blank(), 
              legend.position = "bottom",
              plot.title=element_text(hjust=0.5)) +
        labs(title=i)
    print(gg1)
  }
}, movie.name="test.gif", ani.height=500, ani.width=500*3)

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Thanks for the response - using `animation` is definitely workable, although from looking briefly at the documentation it doesn't appear to offer the same control over transitions that `gganimate` does. But it's definitely an option if `waffle` and `gganimate` are incompatible! – jllls Sep 08 '19 at 16:24