gganimate issue with geom_bar?

2020-03-13 08:32发布

问题:

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)

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)

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

回答1:

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)

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

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