Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I was inspired by a few animated gifs that I saw recently so I decided to make one of my own. For this project, I sought out a way to effectively visualize how Mcdonald’s expanded throughout the world. To do this, I created a heatmap of the world and using animations I was able to efficiently map out how McDonald’s became more popular over time.
The data I am using is from this Wikipedia page. It took a small amount of manual cleaning before I could import it into R just because some of the countries’ spellings from this article did not match with what is used in the R ‘maps’ package.
< !--more-->1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | library(ggplot2) library(maps) library(mapproj) library(lubridate) library(animation) mcdonalds <- read.csv("mcdonalds.csv", header = TRUE) mcdonalds$region <- mcdonalds$Country mcdonalds <- mcdonalds[, 2:3] world <- map_data("world") merged.data <- merge(world, mcdonalds, sort=FALSE, by = "region") merged.data <- merged.data[order(merged.data$order), ] merged.data$Year <- as.numeric(merged.data$Year) plotIfStore <- function(x) { df = subset(merged.data, Year <= x) g <- ggplot() + geom_path(aes(x = long, y = lat, group = group), data = world) g <- g + ggtitle("Growth of Mcdonalds from 1940-2011") g <- g + geom_polygon(aes(x = long, y = lat, group = group, fill = "red"), data = df) g <- g + annotate("text", x = 220, y = 0, label = x, col = "blue") g <- g + theme(legend.position = "none") g <- g + xlab(NULL) + ylab(NULL) g <- g + theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank()) g <- g + opts(axis.text.x = theme_blank(), axis.text.y = theme_blank()) } plot <- function(x) print(plotIfStore(x)) ani.options(ani.width = 621, ani.height = 357) saveGIF(for (i in 1940:2011) plot(i), convert = "gm convert", cmd.fun = shell, clean = T, outdir = getwd()) |
The .gif starts from year 1940 – the year when the first McDonald’s opened in the US. There is a bit of downtime between 1940 and 1967 before McDonald’s expands to Canada. After that, the company rapidly takes off all over the globe.
The animation package is phenomenal and makes use of GraphicsMagick. That part alone took me over an hour to figure out because command line typing on Windows is absolutely terrible.
Please e-mail or leave a comment if you have any questions – I would be happy to help you understand the code better.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.