Showing posts with label visualization. Show all posts
Showing posts with label visualization. Show all posts

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. 

Friday, November 15, 2024

Day 5: 30-days to learn rgl, plotly, and gganimate - Practice rgl customization (lighting, colors, sizes) and apply labels and text to 3D points



Step 1: Create a Basic 3D Plot

We'll begin by creating a simple 3D scatter plot to serve as our canvas for customization.

# Load the rgl package
library(rgl)
 
# Sample data for 3D scatter plot
set.seed(123)
x <- rnorm(10)
y <- rnorm(10)
z <- rnorm(10)
 
# Basic 3D scatter plot
plot3d(x, y, z, type = "s", col = "blue", size = 2)

This creates a simple 3D scatter plot with blue points.

Step 2: Customize Point Colors, Sizes, and Shapes

Adjusting colors, point sizes, and shapes can make the plot more visually informative.

# Customizing colors, sizes, and shapes
point_colors <- rainbow(length(x))  # Assign each point a different color
plot3d(x, y, z, col = point_colors, size = 5, type = "s")  # Increased size

In this example:

  • Each point gets a unique color.
  • size controls the size of the points (default is smaller; try 5 for larger points).
  • type = "s" sets the points as spheres.

Step 3: Add Lighting Effects

Lighting can add depth and realism to your plot.

# Adding lighting effects
open3d()  # Open a new rgl window
plot3d(x, y, z, col = point_colors, size = 5, type = "s")
 
# Adjust lighting - you can experiment with these settings
rgl.light(ambient = "#FFFFFF", specular = "#BBBBBB", diffuse = "#888888", x = 1, y = 1, z = 1)

Lighting parameters:

  • ambient: Light that scatters evenly.
  • specular: Shiny highlights on objects.
  • diffuse: Light scattered by the surface.

Experiment with these values to get the desired effect.

Step 4: Customize Camera Angles and Views

You can set the viewing angle to emphasize specific points or sections.

# Adjust camera angle
rgl.viewpoint(theta = 30, phi = 30, fov = 60)

Parameters:

  • theta and phi: Control the angles from which the plot is viewed.
  • fov: Field of view; increasing it creates a wide-angle view, while lowering it zooms in.

Step 5: Add Labels and Text to 3D Points

Labels help make your data points identifiable, enhancing interpretability.

# Adding labels to each point
text3d(x, y, z, texts = paste("Pt", 1:10), col = "black", cex = 0.8)

Explanation:

  • text3d: Adds text at each point’s location.
  • texts: Vector of labels for each point.
  • col and cex: Customize text color and size.

Step 6: Experiment with Size and Color Gradients

You can set sizes and colors based on data values to make plots more meaningful.

# Adjust point sizes and color gradient based on z-values
size_values <- rescale(z, to = c(3, 10))  # Scale sizes between 3 and 10
color_gradient <- heat.colors(length(z))
 
plot3d(x, y, z, col = color_gradient, size = size_values, type = "s")

Step 7: Adding Legends for Better Interpretation (Optional)

Legends help viewers interpret what different colors or sizes represent.

# Add a simple legend to the plot
legend3d("topright", legend = c("Low", "Medium", "High"), pch = 16, col = c("blue", "green", "red"), cex = 1.2)

Step 8: Save the Interactive 3D Plot (Optional)

To save your 3D plot as an HTML file for interactive viewing:

# Save as HTML file for interactive use
rglwidget() %>% htmlwidgets::saveWidget("3Dplot.html")

This file can then be shared or viewed interactively in a browser.

Summary

Today, you customized an rgl 3D plot by:

  • Adjusting lighting, colors, sizes, and shapes.
  • Adding text labels to 3D points for better interpretation.
  • Experimenting with camera angles and views.