我如何使 gganimate 从数据集中指定的零开始为柱形图设置动画

How can I make gganimate animate a column chart by starting at zero as specified in the dataset

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

谁能修改代码,使公司 A 的动画从 0 而不是 5 开始?

 library(ggplot2)
 library(gganimate)
 year<-c(2018,2018,2019,2019,2020,2020)
 country<-c("USA","USA","USA","USA","USA","USA")
 company<-c("A","B","A","B","A","B")
 profit<-c(0,5,-2,2,0,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') 

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

 library(ggplot2)
 library(gganimate)
 year<-c(2018,2018,2019,2019,2020,2020)
 country<-c("USA","USA","USA","USA","USA","USA")
 company<-c("A","B","A","B","A","B")
 profit<-c(0,5,-2,2,0,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')