The maps package produces pretty rudimentary maps which you can use for your visualizations. ggmap is the package that you’ll want to use if you want a more detailed map as background to your visualizations. In what follows, we’ll demonstrate how to use ggmap with the Sacramento dataset in the caret package:

library(caret)
library(dplyr)
library(ggmap)

data(Sacramento)
df <- Sacramento %>%
    group_by(city) %>%
    summarize(
        median_price = median(price),
        transactions = n(),
        latitude = mean(latitude),
        longitude = mean(longitude))

Google maps

It turns out that using Google maps as a background is quite a challenge now. To do so, you need to provide an API key and enable billing. See https://github.com/dkahle/ggmap for more details on how to work with these new restrictions.

Stamen maps

Fortunately there is an easier way to get maps which are more sophisticated than those provided by the maps package: Stamen maps. The code below is an example of how to get a map from Stamen maps (the get_stamenmap function belongs to the ggmap package.)

height <- max(Sacramento$latitude) - min(Sacramento$latitude)
width <- max(Sacramento$longitude) - min(Sacramento$longitude)
sac_borders <- c(bottom  = min(Sacramento$latitude)  - 0.1 * height, 
                 top     = max(Sacramento$latitude)  + 0.1 * height,
                 left    = min(Sacramento$longitude) - 0.1 * width,
                 right   = max(Sacramento$longitude) + 0.1 * width)

map <- get_stamenmap(sac_borders, zoom = 10, maptype = "toner-lite")
ggmap(map)

Notice that a bunch of messages are printed showing what files are being loaded. To remove these messages from your report, include the option “message=FALSE” at the top of your R chunk.

By default, the zoom parameter is set to 10. Making it bigger gives a more detailed map, but takes longer to load.

Just like in ggplot2 graphics, we can add layers to the map drawn by ggmap(map) with the + syntax. For example, if we wanted to overlay the map with the data from our Sacramento dataset, we could do the following:

ggmap(map) +
    geom_point(
        data = df,
        mapping = aes(x = longitude, y = latitude, 
                      col = median_price, size = transactions)) +
    scale_color_distiller(palette = "YlOrRd", direction = 1)

Another way to get Stamen maps as a background is to use the qmplot function. Notice though that the syntax is pretty different from what we had with ggplot. Here is a map plotting the same points as above but with a different color scale:

qmplot(x = longitude, y = latitude, data = df, maptype = "watercolor", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

The full list of map types is “terrain”, “terrain-background”, “terrain-labels”, “terrain-lines”, “toner”, “toner-2010”, “toner-2011”, “toner-background”, “toner-hybrid”, “toner-labels”, “toner-lines”, “toner-lite”, “watercolor”. Note that some of them don’t work with the CRAN version of ggmap (e.g. “terrain”); instead, you will have to download the github version of the package (see https://github.com/dkahle/ggmap/issues/188).

Below are examples of what “terrain” and “toner” look like:

qmplot(x = longitude, y = latitude, data = df, maptype = "terrain", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

qmplot(x = longitude, y = latitude, data = df, maptype = "toner", 
       geom = "point", color = median_price, size = transactions) +
    scale_color_gradient(low = "blue", high = "red")

Session info

sessionInfo()
## R version 3.6.3 (2020-02-29)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 19.10
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
## LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.3.7.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggmap_3.0.0     dplyr_0.8.5     caret_6.0-86    ggplot2_3.3.0  
## [5] lattice_0.20-41
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.4.6         lubridate_1.7.8      tidyr_1.0.2         
##  [4] png_0.1-7            class_7.3-16         assertthat_0.2.1    
##  [7] digest_0.6.25        ipred_0.9-9          foreach_1.5.0       
## [10] R6_2.4.1             plyr_1.8.6           stats4_3.6.3        
## [13] evaluate_0.14        httr_1.4.1           pillar_1.4.3        
## [16] RgoogleMaps_1.4.5.3  rlang_0.4.5          curl_4.3            
## [19] data.table_1.12.8    rpart_4.1-15         Matrix_1.2-18       
## [22] rmarkdown_2.1        labeling_0.3         splines_3.6.3       
## [25] gower_0.2.1          stringr_1.4.0        munsell_0.5.0       
## [28] compiler_3.6.3       xfun_0.12            pkgconfig_2.0.3     
## [31] htmltools_0.4.0      nnet_7.3-13          tidyselect_1.0.0    
## [34] tibble_3.0.0         prodlim_2019.11.13   codetools_0.2-16    
## [37] fansi_0.4.1          crayon_1.3.4         withr_2.1.2         
## [40] MASS_7.3-51.5        bitops_1.0-6         recipes_0.1.12      
## [43] ModelMetrics_1.2.2.2 grid_3.6.3           nlme_3.1-145        
## [46] gtable_0.3.0         lifecycle_0.2.0      magrittr_1.5        
## [49] pROC_1.16.2          scales_1.1.0         cli_2.0.2           
## [52] stringi_1.4.6        farver_2.0.3         reshape2_1.4.3      
## [55] sp_1.4-1             timeDate_3043.102    ellipsis_0.3.0      
## [58] generics_0.0.2       vctrs_0.2.4          lava_1.6.7          
## [61] RColorBrewer_1.1-2   rjson_0.2.20         iterators_1.0.12    
## [64] tools_3.6.3          glue_1.4.0           purrr_0.3.3         
## [67] jpeg_0.1-8.1         survival_3.1-11      yaml_2.2.1          
## [70] colorspace_1.4-1     knitr_1.28