如何通过从数据集中指定的零开始使gganimate使柱形图动画化

问题描述

我正在使用gganimate制作动画的柱形图。 参见下面的示例代码。 问题在于,在该示例中,公司A在2018年实现了零利润,在2019年亏损了-2。我希望公司A的动画从零开始并达到-2,但是从5开始,是B公司在2018年的利润。

任何人都可以修改代码,以便A公司的动画从零开始而不是从5开始?

 library(ggplot2)
 library(gganimate)
 year<-c(2018,2018,2019,2020,2020)
 country<-c("USA","USA","USA")
 company<-c("A","B","A","B")
 profit<-c(0,5,-2,2,0)
 df<-data.frame(year,country,company,profit,stringsAsFactors = FALSE)

 ggplot(data = df,aes(x = country,y = profit,fill=company)) +
 geom_bar(position = "stack",stat ='identity')+
 transition_states(
 year,transition_length = 2,state_length = 1,wrap=FALSE
 )+
 ggtitle('Year: {closest_state}')+
 ease_aes('sine-in-out') 

enter image description here

解决方法

通过将position =“ stack”更改为position =“ identity”解决了此问题。 发生的事情是,2018年来自公司A的0被堆叠在2018年公司B的5个之上。这意味着当它开始为公司A动画的起点是5时。

 library(ggplot2)
 library(gganimate)
 year<-c(2018,2018,2019,2020,2020)
 country<-c("USA","USA","USA")
 company<-c("A","B","A","B")
 profit<-c(0,5,-2,2,0)
 df<-data.frame(year,country,company,profit,stringsAsFactors = FALSE)

ggplot(data = df,aes(x = country,y = profit,fill=company)) +
geom_bar(position = "identity",stat ='identity')+
transition_states(
year,transition_length = 2,state_length = 1,wrap=FALSE
)+
ggtitle('Year: {closest_state}')+
ease_aes('sine-in-out') 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...