Showing posts with label ggplot2. Show all posts
Showing posts with label ggplot2. Show all posts

Tuesday, November 26, 2024

Day 11: 30-days to learn rgl, plotly, and gganimate - Learn How to Save rgl 3D Frames and Stitch Them Into an Animation With gganimate

 

Step 1: Set Up the Environment

1.     Install Required Packages
Ensure you have the following packages installed:

install.packages(c("rgl", "gganimate", "magick"))

The magick package will handle image processing for stitching frames.

2.     Load the Libraries
Load the necessary libraries:

library(rgl)
library(magick)
library(gganimate)

Step 2: Create an rgl 3D Plot

1.     Generate Data for 3D Visualization
Create a 3D dataset for plotting:

set.seed(123)
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)
colors <- rainbow(100)
 
# Create a 3D scatter plot
plot3d(x, y, z, col = colors, size = 5, type = "s")

2.     Set Up Rotation or Camera Movements
Define the rotation sequence or camera viewpoints:

n_frames <- 36  # Number of frames
angles <- seq(0, 360, length.out = n_frames)

Step 3: Save rgl Frames

1.     Create a Temporary Directory for Frames
Create a directory to save the images:

dir.create("rgl_frames")

2.     Save Each Frame
Loop through the angles and save an image for each:

for (i in seq_along(angles)) {
    rgl.viewpoint(theta = angles[i], phi = 30, fov = 60)
    snapshot3d(sprintf("rgl_frames/frame_%03d.png", i))
}

Step 4: Combine Frames Into an Animation

1.     Use magick to Stitch Images
Load and combine the images:

frames <- list.files("rgl_frames", full.names = TRUE, pattern = "png")
animation <- image_read(frames) %>%
             image_animate(fps = 10)  # Set frames per second

2.     Save the Animation
Save the animation as a GIF:

image_write(animation, "rgl_animation.gif")

Step 5: (Optional) Combine With gganimate

1.     Create a Data Frame for gganimate
If you want to integrate gganimate, create a dataset representing each frame's data:

animation_data <- data.frame(
    x = rep(x, n_frames),
    y = rep(y, n_frames),
    z = rep(z, n_frames),
    frame = rep(1:n_frames, each = length(x))
)

2.     Visualize With ggplot2 and gganimate
Use ggplot2 to create a dynamic scatter plot:

library(ggplot2)
ggplot(animation_data, aes(x = x, y = y, color = z, frame = frame)) +
    geom_point() +
    transition_manual(frame) +
    theme_minimal()

Step 6: Clean Up

1.     Remove Temporary Files
Delete the directory containing frames:

unlink("rgl_frames", recursive = TRUE)

2.     Review the Final Animation
Check the GIF and tweak the settings (e.g., angles, FPS) if needed.


Monday, November 25, 2024

Day 10: 30-days to learn rgl, plotly, and gganimate - Create an Animated Scatter Plot with gganimate and Enhance it with Plotly Hover Details

 

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")

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

Sunday, November 17, 2024

Day 7: 30-days to learn rgl, plotly, and gganimate - Combining gganimate and Plotly for added interactivity

 


Step 1: Install Required Libraries

Ensure you have the necessary libraries installed and loaded:

install.packages("ggplot2")
install.packages("gganimate")
install.packages("plotly")
 
library(ggplot2)
library(gganimate)
library(plotly)

Step 2: Create an Animated Plot with gganimate

We’ll first create a simple animated scatter plot showing the movement of points over time.

  1. Prepare the Data:
# Sample data for animation
set.seed(42)
data <- data.frame(
  x = rnorm(50),
  y = rnorm(50),
  time = rep(1:5, each = 10),
  group = rep(letters[1:10], times = 5)
)
  1. Create the Animated Plot:
# Animated scatter plot with gganimate
p <- ggplot(data, aes(x = x, y = y, color = group)) +
  geom_point(size = 4) +
  labs(title = 'Time: {frame_time}', x = 'X-Axis', y = 'Y-Axis') +
  transition_time(time) +
  ease_aes('linear')
 
# Save the animation
anim <- animate(p, nframes = 100, fps = 10, renderer = gifski_renderer())

Step 3: Export Animation Frames

Convert the gganimate frames into individual images that can be used in plotly.

  1. Save Frames:
anim_save("gganimate_frames.gif", animation = anim)

Alternatively, save the individual frames as PNG files:

frame_images <- animate(p, nframes = 100, fps = 10, renderer = file_renderer(dir = "frames", prefix = "frame", overwrite = TRUE))

Step 4: Integrate with plotly for Interactivity

  1. Load Images into plotly: Use plotly to create an interactive slider for the frames.
library(magick)
 
# Load the GIF
frames_gif <- image_read("gganimate_frames.gif")
 
# Extract individual frames
frames_list <- lapply(seq_len(length(frames_gif)), function(i) {
  frame <- image_write(frames_gif[i], format = "png") # Convert frame to PNG format
  list(source = base64enc::dataURI(frame, mime = "image/png")) # Encode as Base64 URI
})
 
# Create the interactive plot
# Create the interactive plot using plotly
plotly_animation <- plot_ly() %>%
  layout(
    sliders = list(list(
      steps = lapply(seq_along(frames_list), function(i) {
        list(
          method = "restyle",
          args = list("images[0].source", frames_list[[i]]$source),
          label = paste("Frame", i)
        )
      })
    ))
  )

# Add the initial image
plotly_animation <- plotly_animation %>%
  add_image(
    source = frames_list[[1]]$source,
    x = 0, y = 0,
    xanchor = "center", yanchor = "middle"
  )


Step 5: Test the Integration

  1. Run the above code to see your animated and interactive plot in the RStudio Viewer or browser.
  2. Experiment with the hover, zoom, and pan features provided by plotly.

Step 6: Reflect and Experiment

  • Experiment with more complex gganimate animations, such as using transition_states() or view_follow().
  • Add custom interactivity in plotly, such as hover text and annotations.
N.B: The code may have some errors.