Sunday, November 24, 2024

Day 9: 30-days to learn rgl, plotly, and gganimate - Practice Using Plotly's Interactivity Features with gganimate-Based Animations



Step 1: Load Necessary Libraries

Ensure you have the required packages installed. Use the following code to load them:

# Install required packages if not already installed
install.packages(c("gganimate", "plotly", "ggplot2", "dplyr"))
 
# Load libraries
library(gganimate)
library(plotly)
library(ggplot2)
library(dplyr)

Step 2: Prepare the Dataset

Use a dataset with temporal and categorical components. Here, we'll use the built-in gapminder dataset (install gapminder package if needed).

# Install gapminder if not installed
install.packages("gapminder")
library(gapminder)
 
# Filter dataset for simplicity
data <- gapminder %>% filter(year %in% c(2002, 2007))

Step 3: Create an Animated Plot with gganimate

Generate a simple animated scatter plot showing the relationship between GDP per capita and life expectancy.

# Create the base plot
p <- ggplot(data, aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +
  geom_point(alpha = 0.7) +
  scale_x_log10() + # Log scale for GDP
  labs(title = "Year: {frame_time}", x = "GDP per Capita", y = "Life Expectancy") +
  theme_minimal() +
  transition_time(year) +
  ease_aes('linear')
 
# Animate the plot
animated_plot <- animate(p, nframes = 100, fps = 20, renderer = gifski_renderer())

Step 4: Convert the Animation to Plotly

Extract individual frames from the animation and wrap them into a plotly interactive visualization.

# Convert animation frames to a data frame for Plotly
frame_data <- data %>%
  mutate(frame = as.factor(year))
 
# Create an interactive plot using plotly
interactive_plot <- plot_ly(
  data = frame_data,
  x = ~gdpPercap,
  y = ~lifeExp,
  size = ~pop,
  color = ~continent,
  frame = ~frame,
  text = ~paste("Country:", country, "<br>Life Expectancy:", lifeExp, "<br>GDP per Capita:", gdpPercap),
  hoverinfo = "text",
  type = 'scatter',
  mode = 'markers',
  marker = list(opacity = 0.7)
)
 
interactive_plot <- interactive_plot %>%
  layout(
    title = "Interactive Animation: Life Expectancy vs GDP",
    xaxis = list(title = "GDP per Capita (Log Scale)", type = "log"),
    yaxis = list(title = "Life Expectancy")
  )

Step 5: Add Zoom and Pan Interactivity

Enable zoom and pan features to enhance the user experience.

interactive_plot <- interactive_plot %>%
  layout(dragmode = "zoom") %>%
  config(scrollZoom = TRUE)
 
# View the interactive plot
interactive_plot

No comments: