user75252
user75252

Reputation: 309

Animate plot containing both bar and line plots using R

I have data of this format:

head(data)
year    price   profit
2018    3185.96   9
2017    3249.69   10
2016    3005.24   6
2015    3739.79   17
2014    2238.22   15

I want get the price variable as bar and profit as line with year as x-axis and animate the plot using gganimate. I can plot a static plot of both the variables using 2 y axis this way :

p1 <- ggplot(data) + geom_bar(aes(year, price, fill = year), stat = 'identity') +
  geom_line(aes(year, profit*100)) +
  scale_y_continuous(name = 'Price',sec.axis = sec_axis(~./100, 'Profit%')) 

enter image description here or have a facet grid this way:

long <- pivot_longer(data, -year, names_to = 'Category', values_to = 'Value')

p2 <- ggplot(long, aes(year, Value)) + facet_grid(Category~., scales = 'free') +
  geom_bar(data = long[long$Category == 'price', ], stat = 'identity') +
  geom_line(data = long[long$Category == 'profit', ])

The problem is that I am unable animate either of the plots using gganimate such that past values/bars are shown in the plot as it progresses through the year variable.

If I use transition_time or transition_states along with shadow_mark, I am unable to plot the line, whereas if I use transition_reveal to get the line, the past years bars are fading away.

enter image description here

I need to have both the bar and line progressing through years while retaining the past values.

Upvotes: 1

Views: 309

Answers (1)

DJV
DJV

Reputation: 4873

I think that what you're looking for is transition_manual():

library(tidyverse)
library(gganimate)

data %>%
  ggplot(aes(year, price, fill = year)) + 
  geom_bar(stat = 'identity') +
  geom_line(aes(year, profit*100)) +
  scale_y_continuous(name = 'Price',
                     sec.axis = sec_axis(~./100, 'Profit%')) + 
  transition_manual(year, cumulative = TRUE)

enter image description here

Upvotes: 2

Related Questions