gganimate stacked bar chart over time

安稳与你 提交于 2020-01-16 14:10:12

问题


I am trying to animate a stacked bar chart over time. In particular, I would like each stack to first build up in a given year and then transition to the next year. Also, I would like to make sure the past bars are visible. The following code plots each bar at once and transitions to the next year while making the previous years invisible. Is there a way to solve this issue?

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:


If you make your data look like this:

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))

You can animate over ID instead of Year and it builds sequentially. Group 1 is 2010, group 2 is 2010 and 2011, and group 3 is 2010, 2011, and 2012

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


来源:https://stackoverflow.com/questions/54045103/gganimate-stacked-bar-chart-over-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!