Hey guys. I've been struggling to create an animated data over time bar chart for months now. My goal is to have bars that slide and overtake each other depending on their values. I've got a basic version of this working using geom_tile. Here's my current plot:
https://i.imgur.com/8OHoHpZ.mp4
The problems I can't seem to solve are:
1. I need the graph to only focus on the top 10 ranking values at any time. Right now it is squishing all values onto the screen which makes them very small and overwhelming to the viewer.
The image below is what I'm trying to achieve. It only shows the top 10 bars on screen. The bars below that slide out of view, keeping the plot simple visually.
2. Including images for each bar. You can also see this effect in the example above. (Picture of a person, company logo etc.)
I think I can accomplish this with geom_image? I've gotten images to work with a static plot but I'm not sure how to make it work with an animated geom_tile plot.
3. Scale the plot to the maximum current value on screen, not the maximum value of all time. Currently most of my bars are very small due to the plot being scaled by the highest value ever seen in the data.
I greatly appreciate any help. Very sorry if these are obvious questions. I've looked around quite a but but can't seem to find answers to these. I'm sure you can tell I'm a big noob with R and RStudio.
If anyone can tell me how to solve even one of these issues it would be a huge help to me. Thank you for your time!
Here's my plot's R code:
library(tidyverse)
library(gganimate)
library(gapminder)
library(av)
theme_set(theme_classic())
dataForAnim <- gapminder %>%
filter(continent == "Americas") %>%
group_by(year) %>%
# The * 1 makes it possible to have non-integer ranks while sliding
mutate(rank = min_rank(-gdpPercap) * 1) %>%
ungroup()
animatedPlot <- ggplot(dataForAnim, aes(rank, group = country,
fill = as.factor(country), color = as.factor(country), height=.5)) +
geom_tile(aes(y = gdpPercap/2, height = gdpPercap, width = 0.9), alpha = 0.8, color = NA) +
# text in x-axis (requires clip = "off" in coord_*)
# paste(country, " ") is a hack to make pretty spacing, since hjust > 1
# leads to weird artifacts in text spacing.
geom_text(aes(y = 0, label = paste(country, " ")), vjust = 0.2, hjust = 1) +
coord_flip(clip = "off", expand = FALSE) +
scale_y_continuous(labels = scales::comma) +
scale_x_reverse() +
guides(color = FALSE, fill = FALSE) +
labs(title='{closest_state}', x = "", y = "GFP per capita") +
theme(plot.title = element_text(hjust = 0.5, size = 32),
axis.ticks.y = element_blank(), # These relate to the axes post-flip
axis.text.y = element_blank(), # These relate to the axes post-flip
plot.margin = margin(1,1,1,4, "cm")) +
transition_states(year, transition_length = 4, state_length = 1) +
ease_aes('cubic-in-out')
animatedPlot