问题描述
我正在使用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')
解决方法
通过将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')