Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206235

How can I make the bars in this ggplot appear with gganimate?

$
0
0

I am newbie with R but have some time on my hands and am trying some stuff out. What I like most is animating graphs/plots so that's what I am trying to do. I want to create a plot where you can compare the season of two different sports teams. The graph shows wins and losses correctly when I don't add any animations, but as soon as I try something it starts acting weird.

My animated plot at the moment

Here is my code:

#Libraries
library(ggplot2)
library(gganimate)
library(gifski)
library(png)

#Data
gameNumber <- c(1,2,3,1,2,3)
team <- c("PBJ", "PBJ", "PBJ", "KFC", "KFC", "KFC")
teamWonTheGame <- c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE)
runsEarned <- c(3, 4, 2, 10, 4, 6)
runsAllowed <- c(0, 5, 1, 3, 8, 12)
runDifference <- runsEarned-runsAllowed

mydata <- data.frame(gameNumber, team, runDifference)

#Main Plot
plot <- ggplot(mydata, aes(x=gameNumber, y=runDifference, fill=teamWonTheGame)) + 
  geom_bar(stat = "Identity") +
  ylab("Difference in Points") +
  xlab("Game No.") +
  ggtitle("Results for the Season") +
  scale_fill_manual(name="Outcome",
                    values = c("TRUE" = "green", "FALSE" = "red"),
                    breaks=c("TRUE", "FALSE"),
                    labels=c("Win", "Loss")) 

#correct plot without animation
plot + facet_wrap( ~ team, ncol=1) + 
  theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank())

#incorrect plot with animation
plot + facet_wrap( ~ team, ncol=1) + 
  theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank()) +
  transition_reveal(gameNumber)

How can I get the bars to "grow" from the middle (y=0) and not fly in from the side? I would be happy if they just appear and don't "grow", but if possible it would be cool. Also, can I stop the animation after one complete cycle? Or does it always loop?


Viewing all articles
Browse latest Browse all 206235

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>