我有一个用ggplot创建的条形图,我想对其进行动画处理;基本情节是...
我已经在网上对此进行了研究并创建了以下代码:-
这里有一些Reprex数据...
Data <- as.data.frame(rbind(c("11 Mar'", "Male", "20-30"),
c("11 Mar'", "Male", "20-30"),
c("11 Mar'", "Female", "20-30"),
c("12 Mar'", "Female", "50-60"),
c("12 Mar'", "Female", "10-20"),
c("12 Mar'", "Male", "60-70"),
c("13 Mar'", "Female", "20-30"),
c("13 Mar'", "Female", "60-70"),
c("13 Mar'", "Male", "60-70"),
c("13 Mar'", "Male", "60-70"),
c("13 Mar'", "Female", "20-30"),
c("14 Mar'", "Female", "70-80"),
c("14 Mar'", "Female", "70-80"),
c("14 Mar'", "Male", "40-50")))
colnames(Data) <- c("Date", "Sex", "AgeGroup")
这是我给ggplot的电话...
ggplot(Data, aes(x = AgeGroup, fill = Sex, frame = Date, Cumulative = TRUE)) +
geom_bar(position = position_dodge2(preserve = "single")) +
scale_fill_manual(values = c("lightblue", "darkblue")) +
xlab("\nAge Group") + ylab("\nIndividuals") +
ggtitle("\nMarch - April 2020") +
scale_y_discrete(limits= c(2,4,6,8)) + theme_pc() +
transition_states(Date, transition_length = 4, state_length = 1) +
labs(title = 'Date: {closest_state}',
subtitle = "Age and Gender distribution",
caption = "data as of 0945 10 Apr 2020")
不幸的是,我没有获得所需的输出-数据未累积显示 取而代之的是,图的每一帧都会刷新以仅显示单日结果。我期望geom_bar 总是会跨天累积数据,但似乎没有-我什至拥有“ Cumulative = TRUE” 在ggplot调用中,但结果仍然是这样...
谁能指出我正确的方向?
答案 0 :(得分:1)
我设法得到它。 我通过复制前一个日期的行并添加到当前日期等来复制数据集。这样频率将是累积的。我无法在R中完成它。但是,数据看起来像这样:
ggplot(Data, aes(x = AgeGroup, fill = Sex, frame = Date)) +
geom_bar(position = position_dodge(preserve = "single")) +
scale_fill_manual(values = c("lightblue", "darkblue"), drop = TRUE) +
xlab("\nAge Group") + ylab("\nIndividuals") +
ggtitle("\nMarch - April 2020") +
scale_y_discrete(limits= c(2,4,6,8)) +
transition_states(Date, transition_length = 4, state_length = 1) + shadow_mark() +
enter_grow() +
exit_fade(alpha = 1)+
labs(title = 'Date: {closest_state}',
subtitle = "Age and Gender distribution",
caption = "data as of 0945 10 Apr 2020")
然后,需要添加具有alpha值的enter_grow()和exit_fade()。确保条形显示的顺序与类别相同。通常,无论颜色如何,都会首先绘制该值的条形图。使得过渡时条形颜色发生变化。
{{1}}