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 installedinstall.packages(c("gganimate", "plotly", "ggplot2", "dplyr")) # Load librarieslibrary(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 installedinstall.packages("gapminder")library(gapminder) # Filter dataset for simplicitydata <- 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 plotp <- 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 plotanimated_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 Plotlyframe_data <- data %>% mutate(frame = as.factor(year)) # Create an interactive plot using plotlyinteractive_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 plotinteractive_plot

No comments:
Post a Comment