Created
May 1, 2019 09:40
-
-
Save halhen/02dd5d3e5e6b3761e3db7490a97d06f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "R Notebook" | |
output: html_notebook | |
--- | |
```{r} | |
library(tidyverse) | |
library(animation) | |
``` | |
# Get some robots out | |
```{r} | |
df.start <- tibble(point = 1:20) %>% | |
mutate(startangle = point / max(point) * 2 * pi, | |
x = 20 * cos(startangle), | |
y = 20 * sin(startangle), | |
direction = startangle - pi / 2) %>% # Turn the robots perpendicular / 90 degrees / pi/2 radians to their position on the circle | |
select(-startangle) | |
df.start %>% | |
ggplot(aes(x, y, xend = x + 1 * cos(direction), yend = y + 1 * sin(direction))) + | |
geom_segment(arrow = arrow(length = unit(0.2, 'cm'))) + | |
coord_equal() | |
``` | |
# Generate the full sequence | |
```{r} | |
df <- df.start | |
df.steps <- tibble() | |
for (step in 1:360) { | |
df <- df %>% | |
mutate(x = x + 0.5 * cos(direction), # <- Change the stepsize here | |
y = y + 0.5 * sin(direction), # <- Change the stepsize here | |
direction = direction - (1 / 360) * pi * 2) # Turn one degree | |
df.steps <- rbind(df.steps, | |
df %>% | |
mutate(step = step)) | |
} | |
``` | |
# Animation | |
```{r} | |
animation_stepsize <- 4 | |
saveGIF({ | |
radius = 40 # max(df.steps$x) | |
for(i in seq(1, 360, by = animation_stepsize)) { | |
p <- df.steps %>% | |
filter(step == i) %>% | |
ggplot(aes(x, y, color = case_when(point == 1 ~ 'red', | |
TRUE ~ 'black'), | |
xend = x + 1 * cos(direction), yend = y + 1 * sin(direction))) + | |
geom_segment(arrow = arrow(length = unit(0.2, 'cm'))) + | |
#geom_segment(data = df.steps %>% # <- uncomment this to plot the red robot's path | |
# filter(point %in% c(1))) + | |
scale_color_identity() + | |
coord_equal(xlim = c(-radius, radius), ylim = c(-radius, radius)) | |
print(p) | |
} | |
}, outdir = getwd(), interval = 3 / (360 / animation_stepsize)) | |
``` | |
# The paths of the robots, making a beautiful donut shape | |
```{r} | |
df.steps %>% | |
ggplot(aes(x, y, color = case_when(point == 1 ~ 'red', | |
TRUE ~ 'black'), | |
xend = x + 1 * cos(direction), yend = y + 1 * sin(direction))) + | |
geom_segment() + | |
scale_color_identity() + | |
coord_equal() | |
``` | |
# The radius of the circle over time | |
```{r} | |
df.steps %>% | |
mutate(r = sqrt(x*x + y * y)) %>% | |
group_by(step) %>% | |
summarize(r = max(r)) %>% | |
ggplot(aes(step, r)) + | |
geom_line() | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment