knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, dev = "ragg_png")
# Create basic scatter plot
library(ggplot2)
library(gapminder)

p <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point(alpha = 0.3, size = 1) + 
  scale_x_log10() +  
  geom_smooth(method = "lm", se = FALSE, color = "black") + 
  labs(title = "Life Expectancy vs GDP per Capita",
       subtitle = "Colored by Continent",
       x = "GDP per Capita (Log scale)",
       y = "Life Expectancy") +
  theme_minimal()

# Show plot
p

p_facet <- p + facet_wrap(~ continent) +
  labs(title = "Life Expectancy vs GDP per Capita by Continent")

# Show plot
p_facet

library(plotly)
library(htmlwidgets)

interactive_plot <- ggplotly(p) 

# Save interactive plot
saveWidget(interactive_plot, "interactive_gapminder_plot.html", selfcontained = TRUE)

print(interactive_plot)
knitr::include_graphics("interactive_gapminder_plot.html")

# Highlight and trace
highlight_continent <- "Asia"
trace_countries <- c("India", "China", "Bangladesh")

# Add flags for highlight/tracing
gapminder <- gapminder %>%
  mutate(
    is_highlighted = ifelse(continent == highlight_continent, "Asia", "Other"),
    is_traced = country %in% trace_countries
  ) %>%
  arrange(country, year)

# Animation plot
p_anim <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, group = country)) +
  # Background
  geom_point(data = filter(gapminder, is_highlighted == "Other"),
             aes(size = pop), color = "grey", alpha = 0.3) +
  # Highlighted continent
  geom_point(data = filter(gapminder, is_highlighted == "Asia"),
             aes(color = country, size = pop), alpha = 0.8) +
  # Traced countries
  geom_path(data = filter(gapminder, is_traced),
            aes(color = country), linewidth = 1.2) +
  geom_text(data = filter(gapminder, is_traced),
            aes(label = country), hjust = 1, vjust = -1, size = 3, show.legend = FALSE) +
  scale_x_log10() +
  scale_size(range = c(2, 10), guide = "none")+
  labs(title = "Year: {frame_time}",
       x = "GDP per Capita (Log Scale)",
       y = "Life Expectancy",
       size = "Population",
       color = "Country") +
  theme_minimal() +
  transition_time(year) +
  ease_aes('linear')

# Save as GIF
anim_save("gapminder_asia_trace.gif",
          animation = animate(p_anim,
                              nframes = 200,
                              fps = 10,
                              width = 1000, 
                              height = 600,
                              units = "px", 
                              renderer = gifski_renderer()))
knitr::include_graphics("gapminder_asia_trace.gif")