Simultaneously move all geom bars according to vote percentage

Viewed 47

I am not able to move all the bars. How do I achieve it? All the bars should start from 0 and move to there desired swing percentage. enter image description here

library(ggplot2)
library(dplyr)
library(gganimate)
theme_set(theme_bw())  
#data <- read.csv("C:\\Daman\\swig.csv")
BHAGWANPUR <- structure(list(STATE = c("UTTARAKHAND", "UTTARAKHAND", "UTTARAKHAND"
), DISTRICT = c("HARDWAR", "HARDWAR", "HARDWAR"), AC = c("BHAGWANPUR", 
"BHAGWANPUR", "BHAGWANPUR"), PARTY = structure(1:3, .Label = c("INC", 
"BJP", "BSP"), class = "factor"), VOTES = c(44882L, 42369L, 4069L
), DELTA_VOTES = c(14835L, 31719L, -32759L), VOTE_PERCENTAGE = c(48.2, 
45.5, 4.4), SWING = c(9.9, 31.9, -42.5), X.CHANGE = c(49.4, 297.8, 
-89), BASE_SHARE = c(38.2, 13.6, 4.4), mpg_type = c("ABOVE", 
"ABOVE", "BELOW")), row.names = c(NA, -3L), class = "data.frame")
BHAGWANPUR$PARTY <- factor(BHAGWANPUR$PARTY,levels=BHAGWANPUR$PARTY)

# Diverging Barcharts
draw <- ggplot(BHAGWANPUR, aes(x=PARTY, y=SWING, label=SWING)) + 
  geom_bar(stat='identity', width=.5,aes(fill=PARTY)) +geom_text(aes(label=SWING,vjust="center"),position = position_stack(vjust = 0.5))+
  scale_fill_manual(values=c("#00BFFF","#F98C1F","#22409A"))+labs(subtitle="Vote swing among parties 2012 to 2017", 
                                                                  title= "Bhagwanpur,Uttarakhand") + 
  coord_flip()+  theme(axis.title.x=element_blank(),axis.title.y=element_blank())+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
                                                                                        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  transition_states(SWING, transition_length = 1, state_length = 1,wrap = TRUE) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

animate(draw, renderer = gifski_renderer())


1 Answers

Here's what you could to to move all the bars simultaneously:

First, add a new column 'state' with states 0 and 1, 0 being the state, where the bars start (at SWING == 0):

BHAGWANPUR <- BHAGWANPUR %>%
  mutate(SWING = 0) %>%
  bind_rows(BHAGWANPUR) %>%
  mutate(state = case_when(SWING == 0 ~ 0,
                           TRUE ~ 1))

Then, add state to transition_states, e. g. like this:

draw <- ggplot(BHAGWANPUR, aes(x=PARTY, y=SWING, label=SWING)) + 
  geom_bar(stat='identity', aes(fill=PARTY)) +
  coord_flip()+
  transition_states(state, wrap=FALSE) +
  enter_grow() +
  ease_aes('sine-in-out')

Now all the bars start at zero and grow simultaneously to the SWING values. I removed exit_shrink and also set wrap = FALSE, so the bars don't move back to zero, but the animation just starts from the beginning.

Related