随时间推移的gganimate堆积条形图

时间:2019-01-04 19:44:02

标签: r gganimate

随着时间的推移,我正在尝试为堆积的条形图制作动画。特别是,我希望每个堆栈首先在给定的一年中建立,然后再过渡到下一年。另外,我想确保过去的酒吧可见。以下代码一次绘制每个条形图,并过渡到下一年,同时使前几年不可见。有办法解决这个问题吗?

library(tidyr)  
library(ggplot2)
library(gganimate)
library(dplyr)

df <- data.frame(stringsAsFactors=FALSE,
                 Year = c("2010", "2011", "2012"),
                 LabelOne = c(1000, 1500, 2000),
                 LabelTwo = c(50, 100, 150),
                 LabelThree = c(20, 30, 40)
)

df_long <- gather(df, lbs, Value, LabelOne:LabelThree, -Year)
head(df_long)

pp <- ggplot(df_long, aes(Year, Value)) +
  geom_bar(stat = "identity", aes(fill = lbs)) +
  transition_states(Year, 
          transition_length = 4, state_length = 2) +
    ease_aes('cubic-in-out')

animate(pp, nframes = 300, fps = 50, width = 400, height = 550)

1 个答案:

答案 0 :(得分:0)

如果您使数据看起来像这样:

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'wav',
        'preferredquality': '192'
    }],
    'postprocessor_args': [
        '-ar', '16000'
    ],
    'prefer_ffmpeg': True,
    'keepvideo': True
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])

您可以在df2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), Year = c(2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 2012L, 2012L, 2012L), lbs = structure(c(1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L), .Label = c("LabelOne", "LabelThree", "LabelTwo"), class = "factor"), Value = c(1000L, 50L, 20L, 1000L, 50L, 20L, 1500L, 100L, 30L, 1000L, 50L, 20L, 1500L, 100L, 30L, 2000L, 150L, 40L)), class = "data.frame", row.names = c(NA, -18L)) 而不是ID上设置动画,并按顺序生成。第1组是2010年,第2组是2010年和2011年,第3组是2010年,2011年和2012年

Year