I want to create an animated barplot with the gganimate package. At the top of plot, I want to put the value of the coresponding year. In my dataset, year value is 1970, 1980, 1990, 2000, 2010. However, when the animatation is shown, I can see year value is overlap to each other as shown in the below picture:
This is my data file: test.csv
This is my code:
library(ggplot2)
library(dplyr)
library(readxl)
library(maps)
library(scales)
library(gganimate)
test_data <- read.csv("test.csv")
male_data <- test_data |> filter(sex_name == "Male") |> group_by(year) |>
arrange(mean_age_death) |>
slice_head(n = 10) |>
mutate(rank_in_year = rank(mean_age_death, ties.method = "first"))|>
ungroup()
male_faceted_plot <- male_data |>
ggplot(aes(x = mean_age_death, y = factor(rank_in_year))) +
geom_col(show.legend = FALSE) +
facet_wrap(vars(year)) +
scale_x_continuous(
limits = c(-50,50),
breaks = seq(0, 50, by = 10)
) +
geom_text(
hjust = "right",
aes(label = country_name),
x = -5,
size = 5
)
male_bar_race <- male_faceted_plot +
# remove faceting
facet_null() +
# label the current year in the top corner of the plot
geom_text(
x = 50, y = 10,
hjust = "top",
aes(label = as.character(year)),
size = 10
) +
# define group structure for transitions
aes(group = country_name) +
# temporal transition - ensure integer value for labeling
transition_states(year, transition_length = 1, state_length = 2, wrap = TRUE)
# basic transition
animate(male_bar_race, nframes = 300, fps = 100, start_pause = 10, end_pause = 10)
How can I fix this? Thanks,
The parameters nframe
(number of frames to render) and fps
(frames per second) should be chosen carefully. Below, you will find my proposal.
male_bar_race <- male_faceted_plot +
facet_null() +
geom_text(
x = 50, y = 10, hjust = "top",
aes(label = year),
size = 10
) +
transition_states(year, transition_length = 1, state_length = 2, wrap = TRUE)
nfr <- length(unique(male_data$year))
animate(male_bar_race, nframes = nfr, fps = 1)
Below is the animation with a smooth transition effect.
male_bar_race <- male_faceted_plot +
facet_null() +
geom_text(
x = 50, y = 10, hjust = "top",
aes(label=sprintf("%4.0f", year)),
size = 10
) +
transition_reveal(year)
animate(male_bar_race, nframes = 40, fps = 10)