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.

No comments: