First time dealing with maps

2015/10/01

Maps

# Installing all the libraries to build maps in R
library(plyr)         # To manipulate data
library(ggplot2)      # To have ggplot2 graphic interface
library(lattice)      # To have Lattice graphic interface
library(rgdal)        # To load "shapefiles" into R and use in conversions of spatial formats 
library(rgeos)        # To use in geometrical operations
library(spatstat)     # To use with Voronoi Tessellation
library(sp)           # Methods for retrieving coordinates from spatial objects.
library(maptools)     # A package for building maps
library(maps)         # A package for building maps
library(RColorBrewer) # To build RColorBrewer color palettes
library(grDevices)    # To build grDevices color palettes
library(reshape2)     # To have more flexibility when transforming data
library(rCharts)      # To create and customize interactive javascript visualizations in R
library(knitr)        # For dynamic report generation in R
library(base64enc)    # Tools for base64 encoding
suppressPackageStartupMessages(library(googleVis)) # To use with Google visualization in R

# setwd("D:\R\MyCodes\Maps")
# setwd("D:\R\MyCodes\Maps")

# First, let's load the first shapefile of Norway into R
# fylke <- readOGR(dsn="/Users/isa/Documents/Courses/Johns Hopkins/RKart_Norge/33_N5000_shape" , layer="NO_Arealdekke_pol")

Hotspots

# TODO Check link to data and set eval TRUE

library(ggmap)
library(maptools)
library(maps)

hotspots <- read.csv("./data/hotspots.csv", sep = ";")
mp <- NULL
mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders
mp <- ggplot() +   mapWorld + geom_point(aes(x=hotspots$longitude, y=hotspots$latitude) ,color="blue", size=3) 
mp

Cities what I visited

Ver1

# Cities
visited <- c("SFO", "Chennai", "London", "Melbourne", "Kuopio")
# visited <- c("Kajaani", "Tampere", "Oulu", "Helsinki", "Kuopio")
ll.visited <- geocode(visited)
visit.x <- ll.visited$lon
visit.y <- ll.visited$lat

# Check longitude and latitude values
#> dput(visit.x)
#c(-122.389979, 80.249583, -0.1198244, 144.96328, 28.06084)
#> dput(visit.y)
#c(37.615223, 13.060422, 51.5112139, -37.814107, -26.1319199)

# # One version to plot is using maps
map("world", fill=TRUE, col="white", bg="lightblue", ylim=c(-60, 90), mar=c(0,0,0,0))
points(visit.x, visit.y, col="red", pch=16)

Or places in Finland:

# Put cities
visited <- c("Kajaani", "Tampere", "Oulu", "Helsinki", "Kuopio")
ll.visited <- geocode(visited)
visit.x <- ll.visited$lon
visit.y <- ll.visited$lat
mapFinland <- borders("Finland", colour="gray50", fill="gray50")
mp <- ggplot() + mapFinland +  geom_point(aes(x=visit.x, y=visit.y) ,color="blue", size=3) 
mp

Ver2

# Put cities
visited <- c("SFO", "Chennai", "London", "Melbourne", "Kuopio")
ll.visited <- geocode(visited)
visit.x <- ll.visited$lon
visit.y <- ll.visited$lat

#Using GGPLOT, plot the Base World Map
mp <- NULL
mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders
mp <- ggplot() + mapWorld
# Now Layer the cities on top
mp <- mp+ geom_point(aes(x=visit.x, y=visit.y) ,color="blue", size=3) 
mp

Map mate

# https://www.r-bloggers.com/mapmate-0-1-0/

devtools::install_github("leonawicz/mapmate")

### SETUP ------
library(mapmate)
library(dplyr)
library(RColorBrewer)
pal <- rev(brewer.pal(11, "RdYlBu"))

data(annualtemps)
data(borders)
data(bathymetry)

id <- "frameID"
temps <- mutate(annualtemps, frameID = Year - min(Year) + 1) %>% filter(frameID == 
                                                                          1)  # subset to first frame
brdrs <- mutate(borders, frameID = 1)
bath <- mutate(bathymetry, frameID = 1)

### FLAT WORLD MAPS VS 3D EARTH --------------------
save_map(temps, id = id, ortho = FALSE, col = "dodgerblue", type = "points", 
         save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = "#FF4500", type = "points", save.plot = FALSE, 
         return.plot = TRUE)

### SIMPLE POINTS -------
save_map(bath, id = id, type = "points", save.plot = FALSE, return.plot = TRUE)

save_map(brdrs, id = id, lon = -70, lat = 40, rotation.axis = 0, type = "maplines", 
         save.plot = FALSE, return.plot = TRUE)


### SPATIAL / POLYGON BOUNDARY LINES
save_map(brdrs, id = id, type = "maplines", save.plot = FALSE, return.plot = TRUE)

### RASTERIZED TILES -------------------
save_map(bath, z.name = "z", id = id, col = pal, type = "maptiles", save.plot = FALSE, 
         return.plot = TRUE)

### FILLED CONTOUR-STYLE DENSITY USING TILES -------
# Default arguments include contour="none" and density.geom="tile".
save_map(bath, z.name = "z", id = id, col = pal, type = "density", save.plot = FALSE, 
         return.plot = TRUE)
# Explicit contour lines can also be overlaid with the base map type.
save_map(bath, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         save.plot = FALSE, return.plot = TRUE)
# Contour lines can also be drawn without including the base layer indicated by type.
save_map(bath, z.name = "z", id = id, col = pal, type = "density", contour = "only", 
         save.plot = FALSE, return.plot = TRUE)
# Contour lines with points
save_map(temps, id = id, col = "red", type = "points", contour = "overlay", 
         save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = "blue", type = "points", contour = "only", save.plot = FALSE, 
         return.plot = TRUE)

### DENSITY MAPS OF LOCATIONS (NO DATA VARIABLE) ------
save_map(temps, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = pal, type = "density", contour = "overlay", save.plot = FALSE, 
         return.plot = TRUE)
# Of course, this would not be interesting to do when the data frame contains gridded data at all lon/lat locations on the world grid like in bathymetry.
save_map(bath, id = id, lon = -70, lat = 50, col = pal, type = "density", contour = "overlay", 
         save.plot = FALSE, return.plot = TRUE)


### Tiles vs. polygons ------------------
# Relying internally on ggplot2::geom_polygon inside save_map can be much faster than ggplot::geom_tile to process the data and make maps. This is an important consideration for generating long sequences of many high-resolution maps. However, the trade off is that polygons may be drawn very poorly with much clipping, the degree of the problem depending on the given data. Of course, if tiles are drawn at an extremely coarse resolution based on the input data, they still won’t look good, and also won’t take as long to draw. It is what you decide to make of it with the data you choose to map. The below examples compare the use of tiles to polygons.
save_map(temps, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         density.geom = "tile", save.plot = FALSE, return.plot = TRUE)
save_map(temps, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         density.geom = "polygon", save.plot = FALSE, return.plot = TRUE)
save_map(bath, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         density.geom = "tile", save.plot = FALSE, return.plot = TRUE)
save_map(bath, z.name = "z", id = id, col = pal, type = "density", contour = "overlay", 
         density.geom = "polygon", save.plot = FALSE, return.plot = TRUE)


save_map(temps, id = id, col = pal, type = "density", contour = "overlay", density.geom = "tile", 
         save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = pal, type = "density", contour = "overlay", density.geom = "polygon", 
         save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = pal, type = "density", ortho = FALSE, contour = "overlay", 
         density.geom = "tile", save.plot = FALSE, return.plot = TRUE)
save_map(temps, id = id, col = pal, type = "density", ortho = FALSE, contour = "overlay", 
         density.geom = "polygon", save.plot = FALSE, return.plot = TRUE)

#### AN EXAMPLE FROM SCRATCH -------------

# polygons
library(rworldmap)
library(rworldxtra)  # required for 'high' resolution map
library(maptools)  # required for fortify to work
# also recommend installing rgeos
spdf <- joinCountryData2Map(countryExData, mapResolution = "high")
spdf@data$id <- rownames(spdf@data)
bio <- ggplot2::fortify(spdf, region = "id") %>% left_join(subset(spdf@data, select = c(id, BIODIVERSITY)), by = "id") %>% mutate(frameID = 1) %>% rename(lon = long)

# raster layer
library(raster)
proj4 <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +to wgs84=0,0,0"
z <- "BIODIVERSITY"
# 1-degree resolution, still somewhat coarse
r <- raster(extent(-180, 180, -90, 90), nrow = 180, ncol = 360, proj4)
bio2 <- rasterize(spdf, r, field = z) %>% rasterToPoints %>% tbl_df() %>% setNames(c("lon", "lat", z)) %>% mutate(frameID = 1)
clrs <- c("royalblue", "purple", "orange", "yellow")
save_map(bio, z.name = z, id = id, lon = -10, lat = 20, col = pal, type = "polygons", 
         save.plot = FALSE, return.plot = TRUE)
save_map(bio2, z.name = z, id = id, lon = -10, lat = 20, col = pal, type = "maptiles", 
         save.plot = FALSE, return.plot = TRUE)