Showing posts with label statistics. Show all posts
Showing posts with label statistics. Show all posts

Thursday, November 21, 2024

Day 8: 30-days to learn rgl, plotly, and gganimate - Creating Animated Plots with gganimate and Exporting Frames to Plotly

 


Step 1: Set Up Your Environment

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

install.packages(c("gganimate", "ggplot2", "plotly"))

  1. Load Libraries:

library(gganimate)

library(ggplot2)

library(plotly)


Step 2: Prepare Your Dataset

  1. Use a time-based dataset or create one for practice. For example:

data <- data.frame(

  year = rep(2000:2010, each = 3),

  category = rep(c("A", "B", "C"), times = 11),

  value = runif(33, 10, 100)

)

  1. Preview your dataset:

head(data)


Step 3: Create a Static ggplot

  1. Start by plotting the data without animation:

p <- ggplot(data, aes(x = year, y = value, color = category)) +

  geom_line(aes(group = category)) +

  theme_minimal() +

  labs(title = "Value Trends Over Time", x = "Year", y = "Value")

  1. Print the plot to ensure correctness:

print(p)


Step 4: Animate the Plot with gganimate

  1. Add animation to visualize trends over time:

animated_plot <- p +

  transition_time(year) +

  ease_aes('linear') +

  labs(subtitle = "Year: {frame_time}")

  1. Render the animation in your RStudio viewer:

animate(animated_plot, nframes = 100, fps = 10)

  1. Save the animation as a GIF (optional):

anim_save("animated_plot.gif", animation = animated_plot)

Step 5: Export Frames to Plotly

Here’s a corrected version of how to export frames to Plotly:


  1. Add a Frame Column: Add a frame column to the dataset for use in plot_ly():

data$frame <- data$year

  1. Create a Plotly Animation: Use plot_ly() to build the animated visualization. Explicitly set the trace type to "scatter" and specify the mode:

plotly_animation <- plot_ly(

  data = data,

  x = ~year,

  y = ~value,

  color = ~category,

  frame = ~frame,

  type = "scatter",

  mode = "lines+markers"

) %>%

  layout(

    title = "Interactive Animation with Plotly",

    xaxis = list(title = "Year"),

    yaxis = list(title = "Value")

  )

  1. Render the Plotly Animation: Display the interactive animated plot:

plotly_animation


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.

Thursday, November 14, 2024

Day 4: 30-days to learn rgl, plotly, and gganimate - Installing rgl and Creating Basic 3D Plots




Step 1: Install and Load rgl

1.     Install the rgl package (if you haven’t already):

install.packages("rgl")

2.     Load the rgl library:

library(rgl)

Step 2: Create a Basic 3D Scatter Plot using plot3d

1.     Generate sample data for plotting:

set.seed(123)
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)

2.     Create a 3D scatter plot using plot3d:

plot3d(x, y, z, col = "blue", size = 5, type = "s")
    • col: Set the color of the points.
    • size: Control the point size.
    • type: "s" represents spheres. You can also try other types, like "p" for points.

The plot should now open in an interactive window, allowing you to view your data in 3D.

Step 3: Create a 3D Scatter Plot using scatter3d

1.     Install and load the car package to access the scatter3d function:

install.packages("car")
library(car)

2.     Use scatter3d for a quick 3D scatter plot:

scatter3d(x, y, z, surface = FALSE, fit = "linear")
    • surface: Set to FALSE if you don't want a regression surface (3D plane).
    • fit: Set to "linear" for a linear fit (you can also use other fits if you like).

Step 4: Exploring Basic Camera Rotations and Zoom Functions

rgl provides several functions to interactively control the camera's view, allowing you to rotate, zoom, and pan.

1.     Rotate the Camera:

    • The rgl.viewpoint() function allows you to set the camera angle. Try the following command:
rgl.viewpoint(theta = 45, phi = 30)
      • theta: Controls rotation around the z-axis.
      • phi: Controls the vertical rotation.

2.     Zoom In and Out:

    • Adjust the zoom level using the zoom parameter in rgl.viewpoint:
rgl.viewpoint(theta = 45, phi = 30, zoom = 0.7)
      • A zoom value less than 1 will zoom out, while a value greater than 1 will zoom in.

3.     Play Around with Different Viewpoints:

    • Experiment with theta, phi, and zoom to see how they change your perspective. Here are a few examples:
# Top-down view
rgl.viewpoint(theta = 90, phi = 90, zoom = 0.5)
 
# Side view
rgl.viewpoint(theta = 0, phi = 0, zoom = 0.8)
 
# Rotate incrementally
for (angle in seq(0, 360, by = 10)) {
  rgl.viewpoint(theta = angle, phi = 30)
  Sys.sleep(0.1)
}

Step 5: Practice and Experiment

Explore rgl further by experimenting with different colors, sizes, and types of points in plot3d, or by adjusting the viewpoint using theta and phi in rgl.viewpoint.

Wednesday, November 13, 2024

Day 3: 30-days to learn rgl, plotly, and gganimate - Dive into 3D plotting with plotly, exploring 3D scatter and surface plots, and customizing axes and color scales




Step 1: Set Up for 3D Plotting

1.     Load plotly: Make sure plotly is loaded in your R environment.

library(plotly)

2.     Create Sample Data: Let’s create sample data for our 3D scatter plot and surface plot.

# Data for 3D Scatter Plot
x_scatter <- rnorm(50)
y_scatter <- rnorm(50)
z_scatter <- rnorm(50)
 
# Data for 3D Surface Plot
x_surface <- seq(-10, 10, length.out = 50)
y_surface <- seq(-10, 10, length.out = 50)
z_surface <- outer(x_surface, y_surface, function(x, y) sin(sqrt(x^2 + y^2)))

Step 2: Create a 3D Scatter Plot

1.     Basic 3D Scatter Plot: Use plot_ly() with type = 'scatter3d' to create a basic 3D scatter plot.

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers')
scatter3d_plot
    • Explanation:
      • x = ~x_scatter, y = ~y_scatter, and z = ~z_scatter: Set the x, y, and z coordinates.
      • type = 'scatter3d': Specifies a 3D scatter plot.
      • mode = 'markers': Displays only markers (points) in 3D space.

2.     Customize Marker Colors and Sizes:

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers',
                          marker = list(size = 5, color = ~z_scatter, colorscale = 'Viridis'))
scatter3d_plot
    • Explanation:
      • size = 5: Adjusts the size of the markers.
      • color = ~z_scatter: Colors markers based on their z values.
      • colorscale = 'Viridis': Applies a color scale to the z values.

Step 3: Create a 3D Surface Plot

1.     Basic 3D Surface Plot: Use plot_ly() with type = 'surface' to create a basic 3D surface plot.

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, type = 'surface')
surface_plot
    • Explanation:
      • z = ~z_surface: Sets the height values of the surface.
      • x = ~x_surface and y = ~y_surface: Sets the x and y coordinates for the surface plot.
      • type = 'surface': Specifies a 3D surface plot.

2.     Customize the Surface Plot with a Color Scale:

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                        type = 'surface', colorscale = 'Viridis')
surface_plot
    • Explanation:
      • colorscale = 'Viridis': Adds a Viridis color scale, enhancing the visualization of depth.

Step 4: Customize Axes

You can adjust the axis properties to improve the plot’s readability and style.

1.     Customize 3D Scatter Plot Axes:

scatter3d_plot <- scatter3d_plot %>%
  layout(scene = list(xaxis = list(title = "X Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      yaxis = list(title = "Y Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      zaxis = list(title = "Z Axis", backgroundcolor = "lightgrey", gridcolor = "white")))
scatter3d_plot
    • Explanation:
      • scene: Defines 3D plot layout options, including xaxis, yaxis, and zaxis.
      • title: Sets custom titles for each axis.
      • backgroundcolor and gridcolor: Adjust axis background and grid colors.

2.     Customize 3D Surface Plot Axes:

surface_plot <- surface_plot %>%
  layout(scene = list(xaxis = list(title = "X Axis", color = "blue"),
                      yaxis = list(title = "Y Axis", color = "green"),
                      zaxis = list(title = "Z Axis", color = "red")))
surface_plot

Step 5: Experiment with Different Color Scales

plotly provides several color scales. Try using different ones to see their effects on your plot.

1.     Apply Different Color Scales to the 3D Scatter Plot:

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers',
                          marker = list(size = 5, color = ~z_scatter, colorscale = 'Cividis'))
scatter3d_plot

2.     Apply Different Color Scales to the 3D Surface Plot:

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                        type = 'surface', colorscale = 'Electric')
surface_plot
    • Other Color Scales:
      • Try color scales like Jet, Bluered, RdBu, YlGnBu, Greens, and Portland to see different effects.

Step 6: Combine All Customizations

Let’s bring everything together to create a polished 3D scatter and 3D surface plot.

Final 3D Scatter Plot with Customizations

final_scatter3d <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                           type = 'scatter3d', mode = 'markers',
                           marker = list(size = 5, color = ~z_scatter, colorscale = 'Viridis')) %>%
  layout(scene = list(xaxis = list(title = "X Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      yaxis = list(title = "Y Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      zaxis = list(title = "Z Axis", backgroundcolor = "lightgrey", gridcolor = "white")))
final_scatter3d

Final 3D Surface Plot with Customizations

final_surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                              type = 'surface', colorscale = 'Electric') %>%
  layout(scene = list(xaxis = list(title = "X Axis", color = "blue"),
                      yaxis = list(title = "Y Axis", color = "green"),
                      zaxis = list(title = "Z Axis", color = "red")))
final_surface_plot

Summary

Today, you:

  • Learned to create 3D scatter and surface plots using plotly.
  • Customized marker colors and sizes for 3D scatter plots.
  • Applied color scales to enhance visual appeal.
  • Customized axes in 3D space, including titles, colors, and backgrounds.

Next, you’ll build on this knowledge by diving into more complex plot customizations and interactive features to make the plots even more informative.