# Load required libraries library(ggplot2) library(animation) # Define the masses masses <- data.frame( mass = c(5, 2, 10), x = c(5, 2, 0), y = c(0, 0, 0) ) # Create a function to rotate the masses rotate_masses <- function(angle) { rotation_matrix <- matrix(c(cos(angle), -sin(angle), sin(angle), cos(angle)), nrow = 2, byrow = TRUE) new_positions <- as.data.frame(as.matrix(masses[, c("x", "y")]) %*% rotation_matrix) colnames(new_positions) <- c("x", "y") return(cbind(masses$mass, new_positions)) } # Create initial plot initial_plot <- ggplot() + geom_point(data = masses, aes(x = x, y = y, size = mass,col=as.factor(mass))) + theme_void()+ theme(legend.position = "none")+ scale_size_continuous(range = c(3, 6)) + xlim(-5, 5) + ylim(-5, 5) + labs(title = "Movement of Masses") # Create animation frames frames <- lapply(seq(0, 2 * pi, by = pi / 36), function(angle) { rotated_masses <- rotate_masses(angle) colnames(rotated_masses) <- c("mass", "x", "y") frame <- initial_plot + geom_point(data = rotated_masses, aes(x = x, y = y, size = mass, col=as.factor(mass))) + theme_void()+ theme(legend.position = "none") return(frame) }) # Save animation ani.options(interval = 0.1) saveGIF({ for (i in 1:length(frames)) { print(frames[[i]]) } }, movie.name = "mass_movement0.gif", ani.width = 600, ani.height = 600, ani.units = "px", ani.type = "cairo") # Load required libraries library(ggplot2) library(animation) # Define the masses masses <- data.frame( mass = c(10, 2, 3), x = c(0, -2, 4), y = c(0, -2, 0), angular_velocity = c(1, 1.5, 0.25) # Angular velocities for each mass ) # Create a function to rotate the masses rotate_masses <- function(angle, angular_velocity) { rotation_matrix <- matrix(c(cos(angle), -sin(angle), sin(angle), cos(angle)), nrow = 2, byrow = TRUE) new_positions <- as.data.frame(as.matrix(masses[, c("x", "y")]) %*% rotation_matrix) colnames(new_positions) <- c("x", "y") return(cbind(masses$mass, new_positions, angular_velocity)) } # Create initial plot initial_plot <- ggplot() + geom_point(data = masses, aes(x = x, y = y, size = mass,col=as.factor(mass))) + theme_void()+ theme(legend.position = "none")+ scale_size_continuous(range = c(3, 6)) + xlim(-5, 5) + ylim(-5, 5) + labs(title = "Movement of Masses") # Create animation frames frames <- lapply(seq(0, 4 * pi, by = pi / 36), function(angle) { rotated_masses <- rotate_masses(angle * masses$angular_velocity, masses$angular_velocity) colnames(rotated_masses) <- c("mass", "x", "y", "angular_velocity") frame <- initial_plot + geom_point(data = rotated_masses, aes(x = x, y = y, size = mass,col=as.factor(mass))) + theme_void()+ theme(legend.position = "none") return(frame) }) # Save animation ani.options(interval = 0.1) saveGIF({ for (i in 1:length(frames)) { print(frames[[i]]) } }, movie.name = "mass_movement.gif", ani.width = 600, ani.height = 600, ani.units = "px", ani.type = "cairo")