2016-04-11 82 views
2

我正在研究一個應該保存爲gif的人口金字塔。 Kind of like in this tutorial of Flowing Data,但用ggplot而不是plotrix在ggplot中設置多個圖的軸

我的工作流程:

1)創建一個人口金字塔

2)在for -loop

for (i in unique(d$jahr)) { 

    d_jahr <- d %>% 
    filter(jahr == i) 

    p <- ggplot(data = d_jahr, aes(x = anzahl, y = value, fill = art)) + 
    geom_bar(data = filter(d_jahr, art == "w"), stat = "identity") + 
    geom_bar(data = filter(d_jahr, art == "m"), stat = "identity") + 
    coord_flip() + 
    labs(title = paste(i), x = NULL, y = NULL) 

    ggsave(p,filename=paste("img/",i,".png",sep="")) 

} 

3中創建多個金字塔-地塊)與animation保存地塊爲gif包

我的問題:

所有年份都有不同的值,所以x軸有不同的範圍。這導致在一個GIF奇怪的外觀,因爲劇情的中心跳到右側,向左,向右...

是否有可能修復x軸(在這種情況下,y軸,因爲coord-flip())在獨立創建的多個圖上?

+0

[如何使一個偉大的R可重現的例子?](http://stackoverflow.com/questions/5963269) – zx8754

+1

也許這個包:https://github.com/dgrtwo/gganimate – zx8754

+0

請閱讀[我如何問一個好問題](http://stackoverflow.com/help/how-to-ask)和[proding一個最小可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a -great-r-reproducible-example#answer-5963610)並相應地編輯你的文章。即,提供輸入數據(虛擬或真實)並將代碼減少到作爲問題一部分的線(例如,問題是ggplot,而不是保存jpeg)。 – lukeA

回答

4

可以通過設置limits參數固定軸的範圍:

library(ggplot2) 
lst <- list(
    data.frame(x = 1:100, y=runif(100, 0, 10)), 
    data.frame(x = 1:100, y=runif(100, 0, 100)) 
) 
ylim <- range(do.call(c, lapply(lst, "[[", "y"))) 
for (x in seq(lst)) { 
    print(ggplot(lst[[x]], aes(x, y)) + geom_point() + scale_y_continuous(limits=ylim)) 
} 

或通過添加+ylim(ylim)代替+scale_y_continuous(limits=ylim)(經由@DeveauP)。

+0

如果是設置限制,'xlim'或'ylim'函數可能比'scale_y_continuous'更合適。 – DeveauP

+0

對,補充說。謝謝! – lukeA

+0

我用'gganimate'包裝去了。工作得很好。 – kbrunner