设置轴值(在动画中)

时间:2017-08-25 21:00:04

标签: r ggplot2 gganimate

如何在动画期间停止Y轴更改?

我制作的图表位于http://i.imgur.com/EKx6Tw8.gif

这个想法是每年制作人口和收入的动画热图。问题是y轴跳转到包括0或有时不包括最高值。你如何稳固地设置轴值?我知道这一定是一个常见的问题,但我找不到答案

重新创建它的代码是

library(gapminder)
library(ggplot2)
library(devtools)
install_github("dgrtwo/gganimate")
library(gganimate)

library(dplyr)
mydata <- dplyr::select(gapminder, country,continent,year,lifeExp,pop,gdpPercap)
#bin years into 5 year bins
mydata$lifeExp2 <- as.integer(round((mydata$lifeExp-2)/5)*5)

mydata$income <- cut(mydata$gdpPercap,  breaks=c(0,250,500,750,1000,1500,2000,2500,3000,3500,4500,5500,6500,7500,9000,11000,21000,31000,41000, 191000),
                             labels=c(0,250,500,750,1000,1500,2000,2500,3000,3500,4500,5500,6500,7500,9000,11000,21000,31000,41000))

sizePer <- mydata%>%
    group_by(lifeExp2, income, year)%>%
    mutate(popLikeThis = sum(pop))%>%
  group_by(year)%>%
      mutate(totalPop = sum(as.numeric(pop)))%>%
    mutate(per = (popLikeThis/totalPop)*100)

sizePer$percent <- cut(sizePer$per,  breaks=c(0,.1,.3,1,2,3,5,10,20,Inf),
                             labels=c(0,.1,.3,1,2.0,3,5,10,20))

saveGIF({
    for(i in c(1997,2002,2007)){
        print(ggplot(sizePer %>% filter(year == i),
     aes(x = lifeExp2, y = income)) +
      geom_tile(aes(fill = percent)) +
                  theme_bw()+
                    theme(legend.position="top", plot.title = element_text(size=30, face="bold",hjust = 0.5))+
                    coord_cartesian(xlim = c(20,85), ylim = c(0,21)) +
  scale_fill_manual("%",values = c("#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"),drop=FALSE)+
annotate(x=80, y=3, geom="text", label=i, size = 6) +
                  annotate(x=80, y=1, geom="text", label="@iamreddave", size = 5) +
   ylab("Income") +   # Remove x-axis label
                  xlab("Life Expenctancy")+
                  ggtitle("Worldwide Life Expectancy and Income")          

        )}
}, interval=0.7,ani.width = 900, ani.height = 600)

1 个答案:

答案 0 :(得分:0)

解决方案:

scale_y_discrete(drop = F)添加到ggplot调用中。 @bdemarest在评论中回答。