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
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
Question: How could I flip the axis of my barchart AND enable a flexible axis?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With