Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animated barplot via gganimate: conflict of view_follow & coord_flip

I want to crate an animated barchart with the gganim package. The coordinates of the barchart should be flipped via coord_flip (i.e. horizontal bars) and the x-axis should be made flexible depending on the length of the bars via view_follow.

Consider the following example data:

# Create example data
df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
                 year = factor(sort(rep(2001:2005, 3))),
                 value = round(runif(15, 0, 100)),
                 group = rep(letters[1:3], 5))

If I create an animated barchart without coord_flip, everything works fine:

library("gganimate")
library("ggplot2")

# Create animated ggplot without coord_flip
ggp <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) +
  view_follow(fixed_x = TRUE) # +
  # coord_flip()
ggp

enter image description here

However, if I add coord_flip, the axes are moving from side to side without any reason:

# Create animated ggplot with coord_flip
ggp2 <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) +
  view_follow(fixed_x = TRUE) +
  coord_flip()
ggp2

enter image description here

Question: How could I flip the axis of my barchart AND enable a flexible axis?

like image 301
Joachim Schork Avatar asked Feb 12 '19 09:02

Joachim Schork


1 Answers

You may want to consider geom_barh from the ggstance package, instead of geom_bar + coord_flip:

library(ggstance)

ggplot(df, aes(y = ordering, x = value)) +
  geom_barh(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) +
  view_follow(fixed_y = TRUE)

animated plot

like image 176
Z.Lin Avatar answered Oct 23 '22 15:10

Z.Lin