iamreddave
iamreddave

Reputation: 39

Set the Axis values (in an animation)

How do I stop the Y-axis changing during an animation?

The graph I made is at http://i.imgur.com/EKx6Tw8.gif

The idea is to make an animated heatmap of population and income each year. The problem is the y axis jumps to include 0 or not include the highest value sometime. How do you solidly set the axis values? I know this must be a common issue but I can't find the answer

The code to recreate it is

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)

Upvotes: 0

Views: 696

Answers (1)

Roman
Roman

Reputation: 4989

Solution:

Adding scale_y_discrete(drop = F) to the ggplot call. Answered by @bdemarest in comments.

Upvotes: 1

Related Questions