我正在尝试建立以下的gif,几乎已经完成,但是,计数器超出了轴,它没有正确显示。问题是我不知道如何或者在哪里改变计数器的位置或者增加x轴。
有什么帮助吗?我发布了完整的代码和检索到的数据和其他图表。
提前谢谢你的时间。
library(quantmod)
library(viridis)
library(scales)
gdp = getSymbols('CLVMNACSCAB1GQES',src='FRED', auto.assign=F)
gdp.df = data.frame(date=time(gdp), coredata(gdp) )
library(data.table)
dt<-data.table(gdp.df)
dt[,year:=year(date)]
dt.y<-dt[, lapply(.SD, mean, na.rm=TRUE), by=year ]
dt.y[,gdp.g:=CLVMNACSCAB1GQES/shift(CLVMNACSCAB1GQES,1,fill=NA)-1]
library(tidyverse)
ggplot(data=dt.y,aes(x=date,y=CLVMNACSCAB1GQES))+geom_line()+
scale_y_log10(label=scales::comma,breaks=c(160000,180000,220000,260000,320000))+
theme_minimal()+theme(plot.caption=element_text(hjust=0))+
labs(x="",y="",title="GDP growth",
subtitle="Annual average, log scale",
caption="Source: U.S. Bureau of Economic Analysis via St Louis Fed FRED database")
ggplot(data=dt.y,aes(x=date,y=gdp.g))+geom_col()+
scale_y_continuous(label=scales::percent)+
theme_minimal()+theme(plot.caption=element_text(hjust=0))+
labs(x="",y="",title="GDP growth",
subtitle="Percent change",
caption="Source: U.S. Bureau of Economic Analysis via St Louis Fed FRED database")
library(animation)
library(tweenr)
myf<-function(y){
dt2<-copy(dt.y)[year>1995 & year<2017]
dt2<-dt2[year > y ,gdp.g:=0]
dt2$yearf<-factor(dt2$year)
dt2$p<-factor(round(dt2$gdp.g*100,1))
dt2$y<-factor(y)
return(as.data.frame(dt2))
}
my.list2<-lapply(c(2016,seq(1996,2016,1)),myf)
tf <- tween_states(my.list2, tweenlength= 2, statelength=3,
ease=rep('cubic-in-out',200), nframes=240)
tf<-data.table(tf)
oopt = ani.options(interval = 0.1)
saveGIF({for (i in 1:max(tf$.frame)) {
g<-ggplot(data=tf[.frame==i],
aes(x=year,y=gdp.g,frame=year,fill=gdp.g,color=gdp.g))+geom_col()+ geom_text(data=tf[.frame==i & yearf==y,],x=2010,y=0.06,
aes(label=paste(yearf,":",p,"%")),family="Arial Black",size=14,alpha=0.75)+
scale_color_viridis(option="D",end=0.9)+
geom_col(data=dt.y[year<2017 & year>1995,],alpha=0,color=NA)+
theme_minimal()+scale_fill_viridis(option="D",end=0.9)+scale_y_continuous(label=percent)+
labs(x="",y="",title="GDP percent change previous year",
caption="Source: U.S. Bureau of Economic Analysis")+
theme(plot.caption=element_text(hjust=0),
plot.title=element_text(face="bold",size=14),
plot.subtitle=element_text(face="italic",size=12),
legend.position="none")
print(g)
ani.pause()
print(paste(i,"out of",max(tf$.frame)))
}
},movie.name="Spain GDP growth.gif",ani.width = 840, ani.height =450)