gganimate与geom_bar有关? [英] gganimate issue with geom_bar?
问题描述
自从大卫·罗宾逊(David Robinson)发布他的gganimate软件包以来,我一直羡慕和钦佩于Twitter上出现的各种ggplot动画,并认为自己会自己玩.使用geom_bar时,我的gganimate有问题.希望下面的示例演示该问题.
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"))
为演示我要执行的操作,我认为绘制由z
刻面的普通ggplot很有用.我正在尝试让gganimate产生一个在这2个图之间循环的gif.
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)
但是当我使用gganimate时,B的图表现很奇怪.在第二帧中,小节从第一帧的小节结束处开始,而不是从原点开始.好像是堆积的条形图.
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)
顺便说一句,当使用geom_point
尝试相同的绘图时,一切都会按预期进行.
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?
预先感谢
托马斯
推荐答案
原因是没有条面,条形图是堆叠在一起的.使用position = "identity"
:
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)
为了避免在这种情况下造成混淆,将frame
替换为fill
(或colour
,具体取决于您所使用的几何图形)更为有用:
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
用frame
替换fill
时绘制的两个图完全对应于排他地一次绘制一种颜色.
The two plots that are drawn, when you replace fill
by frame
correspond exactly to exclusively drawing one of the colours at a time.
这篇关于gganimate与geom_bar有关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!