# Attach packages
library(rearrr)
library(dplyr)
has_ggplot <- require(ggplot2) # Attach if installed
# Set seed
set.seed(4)
# Create a data frame
df <- data.frame(
"x" = 1:50,
"y" = 1,
"r1" = runif(50),
"r2" = runif(50) * 35,
"g" = rep(1:5, each = 10)
)
# Swirl values around (0, 0)
swirl_2d(
data = df,
radius = 45,
x_col = "x",
y_col = "y",
origin = c(0, 0)
)
# \donttest{
# Swirl around the centroid
# with 6 different radius settings
# Scale the distances with custom function
df_swirled <- swirl_2d(
data = df,
radius = c(95, 96, 97, 98, 99, 100),
x_col = "x",
y_col = "y",
origin_fn = centroid,
scale_fn = function(d) {
d^1.6
}
)
df_swirled
# Plot swirls
if (has_ggplot){
df_swirled %>%
ggplot(aes(x = x_swirled, y = y_swirled, color = factor(.radius))) +
geom_point() +
theme_minimal() +
labs(x = "x", y = "y", color = ".radius")
}
# }
#
# Swirl random data
# The trick lies in finding the right radius
#
# Swirl the random columns
df_swirled <- swirl_2d(
data = df,
radius = 5,
x_col = "r1",
y_col = "r2",
origin_fn = centroid
)
# Plot swirls
if (has_ggplot){
df_swirled %>%
ggplot(aes(x = r1_swirled, y = r2_swirled)) +
geom_point() +
theme_minimal() +
labs(x = "r1", y = "r2")
}
Run the code above in your browser using DataLab