ggplot 代码创建一个堆叠条形图,其中df 中的每一行都有一个部分。使用coord_polar,这将成为一个饼图,数据框中的每一行都有一个楔形。然后当您使用gg_animate 时,每个帧仅包含与Y 的给定级别对应的楔形。这就是为什么您每次只能获得完整饼图的一部分。
如果您想要为Y 的每个级别创建一个完整的饼图,那么一种选择是为Y 的每个级别创建一个单独的饼图,然后将这些饼图组合成一个 GIF。这是一个包含一些(我希望)与您的真实数据相似的假数据的示例:
library(animation)
# Fake data
set.seed(40)
df = data.frame(Year = rep(2010:2015, 3),
disease = rep(c("Cardiovascular","Neoplasms","Others"), each=6),
count=c(sapply(c(1,1.5,2), function(i) cumsum(c(1000*i, sample((-200*i):(200*i),5))))))
saveGIF({
for (i in unique(df$Year)) {
p = ggplot(df[df$Year==i,], aes(x="", y=count, fill=disease, frame=Year))+
geom_bar(width = 1, stat = "identity") +
facet_grid(~Year) +
coord_polar("y", start=0)
print(p)
}
}, movie.name="test1.gif")
上面 GIF 中的馅饼都是一样大小的。但是您也可以根据Year 的每个级别的count 的总和来更改馅饼的大小(代码改编自this SO answer):
library(dplyr)
df = df %>% group_by(Year) %>%
mutate(cp1 = c(0, head(cumsum(count), -1)),
cp2 = cumsum(count))
saveGIF({
for (i in unique(df$Year)) {
p = ggplot(df %>% filter(Year==i), aes(fill=disease)) +
geom_rect(aes(xmin=0, xmax=max(cp2), ymin=cp1, ymax=cp2)) +
facet_grid(~Year) +
coord_polar("y", start=0) +
scale_x_continuous(limits=c(0,max(df$cp2)))
print(p)
}
}, movie.name="test2.gif")
如果我可以编辑一下,虽然动画很酷(但饼图并不酷,所以可能动画一堆饼图只会增加侮辱伤害),数据可能会更容易理解一个简单的旧静态线图。例如:
ggplot(df, aes(x=Year, y=count, colour=disease)) +
geom_line() + geom_point() +
scale_y_continuous(limits=c(0, max(df$count)))
或者这样:
ggplot(df, aes(x=Year, y=count, colour=disease)) +
geom_line() + geom_point(show.legend=FALSE) +
geom_line(data=df %>% group_by(Year) %>% mutate(count=sum(count)),
aes(x=Year, y=count, colour="All"), lwd=1) +
scale_y_continuous(limits=c(0, df %>% group_by(Year) %>%
summarise(count=sum(count)) %>% max(.$count))) +
scale_colour_manual(values=c("black", hcl(seq(15,275,length=4)[1:3],100,65)))