# Create map of malaria deaths for all ages across the world and time
malaria_deaths_map %>%
  ggplot() +
  geom_sf(
    aes(fill = deaths), # Map deaths to fill color
    colour = "royalblue4", # Set border color
    linewidth = 0.45 # Set border width
  ) +
  scale_fill_gradientn(colors = custom_palette(30)) + # Use custom color palette
  coord_sf(expand = FALSE) + # Remove extra space around map
  labs(
    title = "Global Malaria Deaths (1990-2016)", # Set map title
    fill = "Deaths (per 100,000 people)" # Set legend title
  ) +
  guides(fill = guide_colorbar(
    barwidth = unit(0.7, "lines"), # Adjust legend width
    barheight = unit(8, "lines") # Adjust legend height
  )) +
  theme(
    plot.title = element_text(margin = margin(b = 15))
  ) # Add margin below title
africa_deaths_data %>%
  ggplot() +
  geom_sf(aes(fill = deaths),
    colour = "royalblue4",
    linewidth = 0.45
  ) +
  scale_fill_gradientn(colors = custom_palette(230)) +
  coord_sf(expand = FALSE) +
  guides(fill = guide_colorbar(
    barwidth = unit(0.7, "lines"),
    barheight = unit(8, "lines")
  )) +
  theme(
    plot.title = element_text(margin = margin(b = 15))
  )

animated_plot2 <- plot2 +
  transition_manual(year) + # Animate by year
  labs(
    title = "Malaria Deaths in Africa (**{current_frame}**)", # Set dynamic title
    fill = "Deaths (per 100,000 people)" # Set legend title
  ) +
  theme(
    plot.title = element_markdown() # Use markdown for dynamic title
  )

# Save the animation as a GIF
anim_save(
  "africa_malaria_animation.gif",
  animation = animated_plot2,
  width = 6,
  height = 8,
  units = "in",
  res = 300,
  nframes = length(unique(africa_deaths_data$year)), # Set number of frames
  fps = 10, # Set frames per second
  renderer = magick_renderer(loop = FALSE) # Use magick renderer
)
asia_deaths_data %>%
  ggplot() +
  geom_sf(aes(fill = deaths),
    colour = "royalblue4",
    linewidth = 0.45
  ) +
  scale_fill_gradientn(colors = custom_palette(30)) +
  coord_sf(expand = FALSE) +
  guides(fill = guide_colorbar(
    barwidth = unit(0.7, "lines"),
    barheight = unit(8, "lines")
  )) +
  theme(
    plot.title = element_text(margin = margin(b = 15))
  )

animated_plot3 <- plot3 +
  transition_manual(year) +
  labs(
    title = "Malaria Deaths in Asia (**{current_frame}**)",
    fill = "Deaths (per 100,000 people)"
  ) +
  theme(
    plot.title = element_markdown()
  )

# Save the animation as a GIF
anim_save("asia_malaria_animation.gif",
  animation = animated_plot3,
  width = 6,
  height = 8,
  units = "in",
  res = 300,
  nframes = length(unique(asia_deaths_data$year)),
  fps = 10,
  renderer = magick_renderer(loop = FALSE)
)