With Christmas tomorrow we have decided to create an animated Christmas
Tree using {ggplot2},
{sf} and
{gganimate}.
First we need a tree. To do this we have used an {sf} polygon where we
pass in the coordinates of the Christmas tree as a list matrix to
st_polygon
. We can then use geom_sf
to add this layer onto a ggplot
object.
library(ggplot2) library(gganimate) library(sf) tree_coords = list( matrix( c(-4, 0, -2.22, 2, -3.5, 2, -1.5, 4, -2.5, 4, -0.8, 6, -1.5, 6, 0, 8, 1.5, 6, 0.8, 6, 2.5, 4, 1.5, 4, 3.5, 2, 2.22, 2, 4, 0, -4, 0), ncol=2, byrow=T ) ) tree = st_polygon(tree_coords) gg_tree = ggplot() + geom_sf(aes(), data=tree) gg_tree
Okay, so now we have a tree shape. Now we need to make it a little more
Christmassy by changing:
- The color using:
fill = "forestgreen", color = "darkgreen"
- Adding the trunk:
geom_rect(aes(xmin = -0.75, xmax = 0.75, ymin = -2, ymax = 0), fill = "saddlebrown", color = "sienna4")
- Add a star on the top:
geom_point(aes(x = 0, y = 8), color = "gold", shape = 8, size = 7, stroke = 3)
- Remove the axis with:
theme_void()
- Set the border:
coord_sf(xlim = c(-6, 6), ylim = c(-4, 10))
- Add a Christmas message:
annotate("text", x = 0, y = 9.5, label = "Merry Christmas \n From Jumping Rivers!", size = 6)
Now our tree looks like this:
gg_tree = ggplot() + geom_sf(aes(), data=tree, fill = "forestgreen", color = "darkgreen") + geom_rect(aes(xmin = -0.75, xmax = 0.75, ymin = -2, ymax = 0), fill = "saddlebrown", color = "sienna4") + geom_point(aes(x = 0, y = 8), color = "gold", shape = 8, size = 7, stroke = 3) + theme_void() + coord_sf(xlim = c(-6, 6), ylim = c(-4, 10)) + annotate("text", x = 0, y = 9.5, label = "Merry Christmas \n From Jumping Rivers!", size = 6) gg_tree
Next we need to use {sf} again to make some lights for the tree then
{gganimate} to make the lights flash.
Placing the points within the boundaries of the tree was a trickier task
than we expected until we fell upon st_sample
which we can pass a
polygon to and it’ll create some sample points within the boundaries. We
also create a vector to colour the points.
points = st_sample(tree, 75) colours = sample(c("red", "yellow", "blue"), 75, replace = TRUE) gg_tree = ggplot() + geom_sf(aes(), data=tree, fill = "forestgreen", color = "darkgreen") + geom_sf(aes(), data=points, color = colours) + geom_rect(aes(xmin = -0.75, xmax = 0.75, ymin = -2, ymax = 0), fill = "saddlebrown", color = "sienna4") + geom_point(aes(x = 0, y = 8), color = "gold", shape = 8, size = 7, stroke = 3) + theme_void() + coord_sf(xlim = c(-6, 6), ylim = c(-4, 10)) + annotate("text", x = 0, y = 9.5, label = "Merry Christmas \n From Jumping Rivers!", size = 6) gg_tree
We can now animate it to make the lights sparkle using transition_time
and ease_aes
:
gg_tree + transition_time(1:75) + ease_aes('linear')
Lastly, have a great Christmas and New Year from the Jumping Rivers
team!
For updates and revisions to this article, see the original post
Related