12.2 Mapping in R

For a video explainer of the code for the applications with maps and color, see below. (Via youtube, you can speed up the playback to 1.5 or 2x speed.)

Install maps package. You only need to do this one time.

install.packages("maps")

All subsequent times, you just need to use library()

library(maps)

The map command is like a plot. It maps a particular entry from a database. Below are a few examples of types of maps that come readymade in the package.

map(database = "world")

map(database = "usa")

map(database = "state")

map(database="county")

You can also map particular regions within a database.

map(database = "state", regions= c("New Jersey", "New York" ))

map(database="county", regions = "Nebraska")

map(database = "world", regions= "Italy")

12.2.1 Using ggplot2 with maps

We may want to embed map in another plotting device that more easily adds informative labels, colors, and other information.

  • While the plotting tools we have worked with before can do this, the function ggplot has a better interface that will more easily help us avoid mistakes, such as putting a label in the wrong place.
install.packages("ggplot2")

Open the packages each time you want to use them.

library(ggplot2)

The “gg” stands for “grammar of graphics.” The ggplot2 package has a very general function ggplot() that provides another system of visualizing data in R.

  • It can be used to plot all kinds of visuals, including scatterplots, barplots, histograms, etc.
  • We are going to focus on its utility for plotting maps, as many new developments in mapping and GIS (geographic information systems) in R use this interface.
  • In ggplot() you add layers to a plot by using + between lines
  • While ggplot() can be applied very widely, we will focus on a more narrow set of applications for mapping.

We will create a map of New Jersey. Similar to before, we will first use a function to pull up map data about U.S. states. The map_data function pulls up just the data instead of making the map itself.

nj_map <- map_data("state",regions= c("New Jersey"))

We also directly integrate the data into the plotting function

## Begin plot
ggplot() + #Note the use of the + sign between each line

  geom_polygon(nj_map, mapping=aes(x=long, y=lat, group=group), 
               colour="black")+
  
  ## add title
  ggtitle("Map of New Jersey")+
  
  ## adjust projection
  coord_quickmap() +
  
  ## remove background
  theme_void() # note: last line does not end with a +