Search code examples
rggplot2gganimate

r gganimate (0.9.9.9) and transform_polygon for radar charts


I'd like to use gganimate to transition through states in a radar chart.

Consider the following example from a post here on Stack Overflow by Curycu :

Closing the lines in a ggplot2 radar / spider chart

library(dplyr)
library(data.table)
library(ggplot2)

rm(list=ls())

scale_zero_to_one <- 
  function(x) {
    r <- range(x, na.rm = TRUE)
    min <- r[1]
    max <- r[2]
    (x - min) / (max - min)
  }

scaled.data <-
  mtcars %>%
  lapply(scale_zero_to_one) %>%
  as.data.frame %>%
  mutate(car.name=rownames(mtcars)) 

plot.data <-
  scaled.data %>%
  melt(id.vars='car.name') %>%
  rbind(subset(., variable == names(scaled.data)[1]))

# create new coord : inherit coord_polar
coord_radar <- 
  function(theta='x', start=0, direction=1){
    # input parameter sanity check
    match.arg(theta, c('x','y'))

    ggproto(
      NULL, CoordPolar, 
      theta=theta, r=ifelse(theta=='x','y','x'),
      start=start, direction=sign(direction),
      is_linear=function() TRUE)
  }

plot.data %>%
  ggplot(aes(x=variable, y=value, group=car.name, colour=car.name)) + 
  geom_polygon(aes(fill=car.name), alpha=0.2) +
  geom_point(size=rel(0.9)) +
  coord_radar() + 
  facet_wrap(~ car.name, nrow=4) + 
  theme_bw() +
  theme(
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.x = element_blank(),
    legend.position = 'none') +
  labs(title = "Cars' Status")

This produces an amazing faceted plot for each car. I made a slight modification to the original code and changed the geom_path to geom_polygon.

Instead of having a facetted graph, I would like to display the plot as a single chart that transitions through the car.name. However, using transition_states produces an error:

plot.data %>%
      ggplot(aes(x=variable, y=value, group=car.name, colour=car.name)) + 
      geom_polygon(aes(fill=car.name), alpha=0.2) +
      geom_point(size=rel(0.9)) +
      coord_radar() + 
      transition_states(car.name, transition_length = 3, state_length = 6) +
      enter_grow() +
      exit_shrink() +
      ease_aes('sine-in-out') +
      theme_bw() +
      theme(
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.x = element_blank(),
        legend.position = 'none') +
      labs(title = "Cars' Status")

Error:

Error in transform_polygon(all_frames, next_state, ease, params$transition_length[i],  : 
  transformr is required to tween polygons

The issue is not specific to geom_polygon, as replacing it with geom_path produces a similar error. Is there a way to modify this to get it to work?


Solution

  • I didn't realize transformr was a different package from thomasp85 that I needed to install.

    devtools::install_github('thomasp85/transformr')