Showing posts with label data. Show all posts
Showing posts with label data. Show all posts

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 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. 

Saturday, November 16, 2024

Day 6: 30-days to learn rgl, plotly, and gganimate - Create an interactive 3D plot with rgl that uses various viewpoints or angles to simulate rotation

rglWebGL


Step 1: Install and Load the rgl Package

Ensure that you have the rgl package installed and loaded in your R environment.

# Install rgl if not already installed
if (!require("rgl")) install.packages("rgl")
 
# Load the rgl package
library(rgl)

Step 2: Prepare a Dataset

For demonstration purposes, create or use a sample 3D dataset (e.g., random points in 3D space).

# Sample dataset with random 3D points
set.seed(123)
n <- 100
x <- rnorm(n)
y <- rnorm(n)
z <- rnorm(n)
colors <- rainbow(n)

Step 3: Create a Basic 3D Plot

Use plot3d() to create a basic 3D scatter plot.

# Create a 3D scatter plot
plot3d(x, y, z, col = colors, size = 5, type = 's', xlab = "X-axis", ylab = "Y-axis", zlab = "Z-axis")

Step 4: Enhance the Plot with Customization

Add customizations like grid lines, labels, and lighting for better visualization.

# Add grid lines
grid3d("x")
grid3d("y")
grid3d("z")
 
# Enhance lighting
light3d(specular = "white")

Step 5: Set Up Rotation Parameters

Define a sequence of angles to rotate the plot and simulate a continuous rotation.

# Define rotation parameters
angles <- seq(0, 360, by = 5) # 5-degree increments

Step 6: Rotate the Plot Programmatically

Use a loop to rotate the plot around a specific axis (e.g., the z-axis).

# Rotate around the z-axis
for (angle in angles) {
  view3d(theta = angle, phi = 30) # Rotate theta; phi is the vertical angle
  Sys.sleep(0.1)                 # Pause for 0.1 seconds for smooth transition
}

Step 7: Export the Visualization

Save the interactive 3D plot as an HTML widget or image file for sharing or further use.

# Save as an interactive HTML file
rglwidget() %>% htmlwidgets::saveWidget("3D_plot_rotation.html")
 
# Save as a static image (PNG)
rgl.snapshot("3D_plot_rotation.png")

Step 8: Test and Adjust

  • Experiment with different rotation axes (x, y, or z) by modifying view3d() parameters.
  • Adjust the speed of rotation using Sys.sleep().

Outcome

By the end of this exercise, you will have an interactive 3D plot that smoothly rotates, providing a dynamic visualization of the data. You can integrate this plot with tools like plotly or embed it into web presentations for a polished output.