Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function to create artifical snow using R base graphics and the animation package
## Licence: GPL 2 or 3 <https://www.gnu.org/licenses/licenses.html#GPL>
## Author: Ioannis Kosmidis <i.kosmidis@ucl.ac.uk>
## Date: 21 December 2017
#' A function to create artifical snow using R base graphics and the animation package
#'
#' @param n_flakes how many flakes to throw?
#' @param fall_speed how fast should the snow fall? There will be a \code{1/fall_speed} seconds delay between moves
#' @param max_flake_size what is the maximum flake size (same as cex in \code{\link{plot}})
#' @param eps how much is the flake allowed to move to the left and to the right? (emulating wind)
#' @param path the path to the file to save the resulting GIF animation
#' @param width in pixels
#' @param height in pixels
#' @param night if \code{TRUE} then dark background otherwise white background
#'
#'
#' @details
#'
#' Result of extreme procrastination before marking pre-Xmas assessments
#'
#' @author Ioannis Kosmidis <i.kosmidis@ucl.ac.uk>
#'
#' @seealso \url{https://paulvanderlaken.com/2017/12/18/generate-snow-in-r/} for another implementation of R snow using \code{ggplot2} and \code{gganimate}
#' @examples
#'
#' if (require("animation") & require("colorspace"))
#' let_it_snow(n_flakes = 400, width = 400, height = 400, night = TRUE)
#'
let_it_snow <- function(n_flakes = 300, fall_speed = 4, max_flake_size = 3, eps = 1e-02, night = TRUE,
path = "~/Downloads/snow.gif", width = 600, height = 600) {
x <- runif(n_flakes)
y <- runif(n_flakes)
sizes <- runif(n_flakes, 0, max_flake_size)
colors <- sequential_hcl(n_flakes, c = c(10, 30), l = c(30, 95), power = 0.7)
epoch <- 0
maxy <- 0.4
saveGIF({
ani.options(interval = 1/fall_speed)
while (any(y > maxy * 3/2)) {
par(mar = rep(1, 4) * 3, bg = if (night) "#001319" else "#F6F6F6")
epoch <- epoch + 1
plot(x, y, xaxt = "n", yaxt = "n", bty = "n", xlab = "", ylab = "",
pch = "*", xlim = c(0, 1), ylim = c(0, maxy), cex = sizes, col = colors)
box(col = "gray", lwd = 10)
abline(h = maxy/2, v = 0.5, col = "gray", lwd = 4)
x <- x + runif(n_flakes, -eps, +eps)
y <- y - runif(n_flakes, 0, 0.02)
ani.pause()
}}, movie.name = path, img.name = "snow", ani.height = height, ani.width = width)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.