Step 1: Install and Load Required Libraries
Ensure you have all the necessary libraries installed. Use the following
code:
install.packages(c("ggplot2", "gganimate", "plotly"))
library(ggplot2)
library(gganimate)
library(plotly)
Step 2: Prepare the Dataset
Use a time-series dataset or create a sample dataset for the scatter plot.
For this example:
set.seed(123)
data <- data.frame(
Time = rep(1:10, each = 10),
X = runif(100, min = 1, max = 100),
Y = runif(100, min = 1, max = 100),
Category = rep(letters[1:10], times = 10)
)
Step 3: Create the Static ggplot
Set up the scatter plot with ggplot2:
static_plot <- ggplot(data, aes(x = X, y = Y, color = Category, frame = Time)) +
geom_point(size = 3) +
labs(title = "Scatter Plot Over Time", x = "X-Axis", y = "Y-Axis") +
theme_minimal()
Step 4: Animate the Plot with gganimate
Use transition_time to
animate the plot over the Time
variable:
animated_plot <- static_plot +
transition_time(Time) +
labs(subtitle = 'Time: {frame_time}')
animate(animated_plot, nframes = 100, fps = 10)
Step 5: Export Animation Frames
Save animation frames for converting to Plotly:
animation_frames <- animate(animated_plot, renderer = file_renderer(dir = "frames", overwrite = TRUE))
Step 6: Convert ggplot to Plotly for Interactivity
Add Plotly's hover functionality to the ggplot-based animation:
plotly_plot <- ggplotly(static_plot, tooltip = c("Category", "X", "Y"))
plotly_plot <- plotly_plot %>%
animation_opts(frame = 1000, redraw = TRUE) %>%
animation_slider(currentvalue = list(prefix = "Time: "))
Step 7: Combine gganimate and Plotly
Overlay gganimate
animations on the interactive Plotly scatter plot:
final_plot <- plot_ly(
data = data,
x = ~X,
y = ~Y,
color = ~Category,
frame = ~Time,
text = ~paste("Category:", Category, "<br>X:", round(X, 2), "<br>Y:", round(Y, 2)),
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
) %>%
layout(
title = "Interactive Scatter Plot with Animation",
xaxis = list(title = "X-Axis"),
yaxis = list(title = "Y-Axis")
)
Step 8: Preview and Save
Render and view the interactive plot:
final_plot
htmlwidgets::saveWidget(final_plot, "animated_scatter_plot.html")