Step 1: Install and Load Required Libraries
Ensure you have all the necessary libraries installed. Use the following
code:
# Install required packages
install.packages
(c("ggplot2",
"gganimate",
"plotly"))
# Load the libraries
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:
# Create a sample dataset
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
:
# Create the base plot
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:
# Animate the scatter plot
animated_plot
<- static_plot
+
transition_time
(Time
)
+
labs
(subtitle
=
'Time: {frame_time}')
# Render the animation (optional, for preview)
animate
(animated_plot
, nframes
=
100, fps
=
10)
Step 5: Export Animation Frames
Save animation frames for converting to Plotly:
# Save each frame
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:
# Convert the static ggplot to a plotly object
plotly_plot
<- ggplotly
(static_plot
, tooltip
=
c("Category",
"X",
"Y"))
# Add animation controls
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:
# Generate the final interactive 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:
# Render the interactive animated plot
final_plot
# Save the plot as an HTML file
htmlwidgets
::saveWidget
(final_plot
,
"animated_scatter_plot.html")
No comments:
Post a Comment