Gganimate problem with geom_bar?

I watched with envy and admiration the various ggplot animations appearing on Twitter since David Robinson released his gganimate package and thought that I would have the game myself. I have a problem with gganimate when using geom_bar. Hope the following example demonstrates the problem.

First, create some data for a reproducible example:

df <- data.frame(x = c(1, 2, 1, 2), y = c(1, 2, 3, 4), z = c("A", "A", "B", "B")) 

To demonstrate what I'm trying to do, I thought it would be useful to build a regular ggplot decorated with z . I am trying to get gganimate to create a gif that cyclically moves between these two graphs.

 ggplot(df, aes(x = x, y = y)) + geom_bar(stat = "Identity") + facet_grid(~z) 

facetted_barchart

But when I use gganimate, the plot for B behaves strangely. In the second frame, bars begin with values ​​that end in the first frames of the frame, and not starting at the origin. As if it were a complex histogram.

 p <- ggplot(df, aes(x = x, y = y, frame = z)) + geom_bar(stat = "Identity") gg_animate(p) 

bars_animation

By the way, when trying the same plot with geom_point everything works as expected.

 q <- ggplot(df, aes(x = x, y = y, frame = z)) + geom_point() gg_animate(q) 

I tried to post some images, but apparently I don't have enough reputation, so I hope this makes sense without them. Is this a mistake, or am I missing something?

Thanks in advance,

Thomas

+7
r ggplot2 gganimate
source share
1 answer

The reason is that the bars add up without cutting. Use position = "identity" :

 p <- ggplot(df, aes(x = x, y = y, frame = z)) + geom_bar(stat = "Identity", position = "identity") gg_animate(p) 

enter image description here

To avoid confusion in such situations, it is much more convenient to replace the frame with fill (or colour , depending on the geometry used):

 p <- ggplot(df, aes(x = x, y = y, fill = z)) + geom_bar(stat = "Identity") p 

enter image description here

The two graphs that are drawn when you replace fill with frame exactly match only one of the colors at a time.

+10
source share

All Articles