# Attach packages
library(rearrr)
library(dplyr)
has_ggplot <- require(ggplot2) # Attach if installed
# Set seed
set.seed(3)
# Create a data frame
df <- data.frame(
"x" = 1:12,
"y" = c(1:4, 9:12, 15:18),
"z" = runif(12),
"g" = rep(1:3, each = 4)
)
# Rotate values 45 degrees around x-axis at (0, 0, 0)
rotate_3d(df, x_col = "x", y_col = "y", z_col = "z", x_deg = 45, origin = c(0, 0, 0))
# Rotate all axes around the centroid
df_rotated <- df %>%
rotate_3d(
x_col = "x",
y_col = "y",
z_col = "z",
x_deg = c(0, 72, 144, 216, 288),
y_deg = c(0, 72, 144, 216, 288),
z_deg = c(0, 72, 144, 216, 288),
origin_fn = centroid
)
df_rotated
# Plot rotations
if (has_ggplot){
ggplot(df_rotated, aes(x = x_rotated, y = y_rotated, color = .degrees_str, alpha = z_rotated)) +
geom_vline(xintercept = mean(df$x), size = 0.2, alpha = .4, linetype = "dashed") +
geom_hline(yintercept = mean(df$y), size = 0.2, alpha = .4, linetype = "dashed") +
geom_line(alpha = .4) +
geom_point() +
theme_minimal() +
labs(x = "x", y = "y", color = "degrees", alpha = "z (opacity)")
}
if (FALSE) {
# Plot 3d with plotly
plotly::plot_ly(
x = df_rotated$x_rotated,
y = df_rotated$y_rotated,
z = df_rotated$z_rotated,
type = "scatter3d",
mode = "markers",
color = df_rotated$.degrees_str
)
}
# \donttest{
# Rotate randomly around all axes
df_rotated <- df %>%
rotate_3d(
x_col = "x",
y_col = "y",
z_col = "z",
x_deg = round(runif(10, min = 0, max = 360)),
y_deg = round(runif(10, min = 0, max = 360)),
z_deg = round(runif(10, min = 0, max = 360)),
origin_fn = centroid
)
df_rotated
# Plot rotations
if (has_ggplot){
ggplot(df_rotated, aes(x = x_rotated, y = y_rotated, color = .degrees_str, alpha = z_rotated)) +
geom_vline(xintercept = mean(df$x), size = 0.2, alpha = .4, linetype = "dashed") +
geom_hline(yintercept = mean(df$y), size = 0.2, alpha = .4, linetype = "dashed") +
geom_line(alpha = .4) +
geom_point() +
theme_minimal() +
labs(x = "x", y = "y", color = "degrees", alpha = "z (opacity)")
}
# }
if (FALSE) {
# Plot 3d with plotly
plotly::plot_ly(
x = df_rotated$x_rotated,
y = df_rotated$y_rotated,
z = df_rotated$z_rotated,
type = "scatter3d",
mode = "markers",
color = df_rotated$.degrees_str
)
}
# \donttest{
# Rotate around group centroids
df_grouped <- df %>%
dplyr::group_by(g) %>%
rotate_3d(
x_col = "x",
y_col = "y",
z_col = "z",
x_deg = c(0, 72, 144, 216, 288),
y_deg = c(0, 72, 144, 216, 288),
z_deg = c(0, 72, 144, 216, 288),
origin_fn = centroid
)
# Plot A and A rotated around group centroids
if (has_ggplot){
ggplot(df_grouped, aes(x = x_rotated, y = y_rotated, color = .degrees_str, alpha = z_rotated)) +
geom_point() +
theme_minimal() +
labs(x = "x", y = "y", color = "degrees", alpha = "z (opacity)")
}
# }
if (FALSE) {
# Plot 3d with plotly
plotly::plot_ly(
x = df_grouped$x_rotated,
y = df_grouped$y_rotated,
z = df_grouped$z_rotated,
type = "scatter3d",
mode = "markers",
color = df_grouped$.degrees_str
)
}
Run the code above in your browser using DataLab