library(magick)
library(ggplot2)
library(dplyr)
library(tidyr)
create a directory to which the images will be written
dir_out <- file.path(tempdir(), “tx-sales”)
dir.create(dir_out, recursive = TRUE)
prepare data
tx_sales <- txhousing %>%
group_by(year,month) %>%
summarise(sales = sum(sales, na.rm = TRUE)) %>%
ungroup() %>%
mutate(month = factor(month, labels = month.name)) %>%
complete(month,year)
get a sorted list of unique years in the TX housing dataset
years <- tx_sales %>%
pull(year) %>%
unique(.) %>%
sort(.)
find the month with the most houses sold to set y axis limit
most_sold <- max(tx_sales$sales, na.rm = TRUE)
loop through years …
subset data …
create barplot of sales by month for each year …
write plot to file
for (y in years) {
p <- tx_sales %>%
filter(year == y) %>%
ggplot(aes(month,sales)) +
geom_col() +
scale_y_continuous(limits = c(0, most_sold), breaks = seq(0,1e5, by = 5000)) +
theme_minimal() +
labs(x = “Month”, y = “Total Properties Sold”, title = y)
fp <- file.path(dir_out, paste0(y, “.png”))
ggsave(plot = p,
filename = fp,
device = “png”)
}
list file names and read in
imgs <- list.files(dir_out, full.names = TRUE)
img_list <- lapply(imgs, image_read)
join the images together
img_joined <- image_join(img_list)
animate at 2 frames per second
img_animated <- image_animate(img_joined, fps = 2)
view animated image
img_animated
save to disk
image_write(image = img_animated,
path = “C:/Users/…./Documents/myRGithub/tx-sales.gif”)
