Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gganimate issue with geom_bar?

I've been looking with envy and admiration at the various ggplot animations appearing on twitter since David Robinson released his gganimate package and thought I'd have a play myself. I am having an issue with gganimate when using geom_bar. Hopefully the following example demonstrates the problem.

First generate 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 plot an ordinary ggplot, facetted by z. I'm trying to get gganimate to produce a gif that cycles between these 2 plots.

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 oddly. In the second frame the bars start at the values that the first frame's bars finish at, rather than starting at the origin. As if it was a stacked bar chart.

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

bars_animation

Incidentally 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 sufficient reputation, so I hope it makes sense without them. Is this a bug, or am I missing something?

Thanks in advance,

Thomas

like image 683
tecb1234 Avatar asked Mar 01 '16 19:03

tecb1234


1 Answers

The reason is that without faceting, the bars are stacked. 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

In order to avoid confusion in situations like this, it is much more useful to replace frame by fill (or colour, depending on the geom you are using`):

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

enter image description here

The two plots that are drawn, when you replace fill by frame correspond exactly to exclusively drawing one of the colours at a time.

like image 147
Stibu Avatar answered Sep 29 '22 07:09

Stibu