geom_bar 的 gganimate 问题?

gganimate issue with geom_bar?

自从 David Robinson 发布了他的 gganimate 包以来,我一直羡慕和钦佩地看着 Twitter 上出现的各种 ggplot 动画,并认为我自己也能玩一玩。我在使用 geom_bar 时遇到 gganimate 问题。希望以下示例可以说明问题。

首先为可重现的示例生成一些数据:

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

为了演示我正在尝试做的事情,我认为绘制一个由 z 分面的普通 ggplot 会很有用。我正在尝试让 gganimate 生成一个在这两个图之间循环的 gif。

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

但是当我使用 gganimate 时,B 的情节表现得很奇怪。在第二帧中,条形图从第一帧条形图结束时的值开始,而不是从原点开始。就好像它是一个堆积条形图。

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

顺便说一句,当用 geom_point 尝试相同的情节时,一切都按预期进行。

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

我尝试 post 一些图像,但显然我没有足够的声誉,所以我希望没有它们也有意义。这是一个错误,还是我遗漏了什么?

提前致谢,

托马斯

原因是没有刻面,条是堆叠的。使用 position = "identity":

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

为了避免在这种情况下出现混淆,将 frame 替换为 fill(或 colour,具体取决于您使用的 geom 会更有用`) :

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

当您将 fill 替换为 frame 时,绘制的两个图完全对应于 独占 一次绘制一种颜色。