|
| 1 | +# Animated Map Gif |
| 2 | +# original source: http://rud.is/b/2013/09/19/animated-irl-pirate-attacks-in-r/ |
| 3 | + |
| 4 | +# load the required packages |
| 5 | +library(maps) |
| 6 | +library(hexbin) |
| 7 | +library(maptools) |
| 8 | +library(ggplot2) |
| 9 | +library(sp) |
| 10 | +library(mapproj) |
| 11 | + |
| 12 | +# download the pirate data shape file |
| 13 | +download.file("http://msi.nga.mil/MSISiteContent/StaticFiles/Files/ASAM_shp.zip", destfile="ASAM_shp.zip") |
| 14 | + |
| 15 | +# unzip the file in the working directory |
| 16 | +unzip("ASAM_shp.zip") |
| 17 | + |
| 18 | +# load the data file "ASAM 05 DEC 13.shp as a dataframe called pirates.df (you'll need to change the file depending on when you download the data) |
| 19 | +pirates.df <- as.data.frame(readShapePoints("ASAM 05 DEC 13")) |
| 20 | + |
| 21 | +# load a map of the world |
| 22 | +world <- map_data("world") |
| 23 | + |
| 24 | +# remove Antarctica |
| 25 | +world <- subset(world, region != "Antarctica") |
| 26 | + |
| 27 | +# create a vector with a list of years we want the data from |
| 28 | +ends <- 1979:2013 |
| 29 | + |
| 30 | +# loop thRough, extRact data, build plot, save plot: BOOM |
| 31 | + |
| 32 | +# for each year in "ends"... |
| 33 | +for (end in ends) { |
| 34 | + # create a 500x250 png containing... |
| 35 | + png(filename=sprintf("arrr-%d.png",end),width=500,height=250,bg="white") |
| 36 | + # create a vector of the dates of the attacks |
| 37 | + dec.df <- pirates.df[pirates.df$DateOfOcc > "1970-01-01" & pirates.df$DateOfOcc < as.Date(sprintf("%s-12-31",end)),] |
| 38 | + # create an element of the first and land attack dates |
| 39 | + rng <- range(dec.df$DateOfOcc) |
| 40 | + # create an employ ggplot |
| 41 | + p <- ggplot() |
| 42 | + # draw a polygon of the world |
| 43 | + p <- p + geom_polygon(data=world, aes(x=long, y=lat, group=group), fill="gray40", colour="white") |
| 44 | + # plot the event data (dec.df) in a hexagon grid |
| 45 | + p <- p + stat_summary_hex(fun="length", data=dec.df, aes(x=coords.x1, y=coords.x2, z=coords.x2), alpha=0.8) |
| 46 | + # create a legend |
| 47 | + p <- p + scale_fill_gradient(low="white", high="red", "Pirate Attacks recorded") |
| 48 | + # make the plot's theme black and white, and change the labels |
| 49 | + p <- p + theme_bw() + labs(x="",y="", title=sprintf("Pirate Attacks From %s to %s",rng[1],rng[2])) |
| 50 | + # make the plot prettier and with a border |
| 51 | + p <- p + theme(panel.background = element_rect(fill='#A6BDDB', colour='white')) |
| 52 | + # view the plot |
| 53 | + print(p) |
| 54 | + # reset devices so it is ready for the next plot |
| 55 | + dev.off() |
| 56 | +} |
| 57 | + |
| 58 | +# run a terminal command to turn all the pngs created in the working directory into one animated gif (requires imagemagick) |
| 59 | +system("convert -delay 45 -loop 0 arrr*g arrr500.gif") |
0 commit comments