Displaying Information with Maps

In this section, we'll create a map of the US and Europe that is colored according to lat, long, and group variables. Let's begin by implementing the following steps:

  1. Install the maps package using map_data to get a data frame for the different states' information, as follows:
states_map <- map_data("state")
glimpse(states_map)
## Observations: 15,537
## Variables: 6
## $ long <dbl> -87.46201, -87.48493, -87.52503, -87.53076, -87.5708...
## $ lat <dbl> 30.38968, 30.37249, 30.37249, 30.33239, 30.32665, 30...
## $ group <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
## $ order <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1...
## $ region <chr> "alabama", "alabama", "alabama", "alabama", "alabama...
## $ subregion <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...

The map_data() function returns a data frame with the following columns:

long: Longitude.

lat: Latitude.

group: This is a grouping variable for each polygon.

A region or subregion can have multiple polygons (for example, if it includes islands).

Now, we can plot the data using geom_polygon() (which can include a color fill)
or geom_path() (which cannot include a color fill). By default, the latitude and longitude will be drawn on a Cartesian coordinate plane, but you can also use coord_map() to specify a projection. The default projection is mercator, which unlike the Cartesian plane, has progressively changing spacing of the grid lines for the latitude lines.

  1. Run the following code to obtain the maps:
ggplot(states_map, aes(x=long, y=lat, group=group)) + geom_polygon(fill="white", colour="black")
ggplot(states_map, aes(x=long, y=lat, group=group)) + geom_path() + coord_map("mercator")

Take a look at the following output screenshots, output 1:

Output 2:


There are a number of different maps available, including the world, France, Italy, the USA (an outline of the United States), states (each state in the USA), and counties (each county in the USA).
  1. For example, we can get the map data for the world, but draw only certain regions, as follows:
#Get map data for world
world_map <- map_data("world")
europe <- map_data("world", region=c("Germany", "Spain", "Italy", "France","UK","Ireland"))
ggplot(europe, aes(x=long, y=lat, group=group, fill=region)) + geom_polygon(colour="black") + scale_fill_ brewer(palette="Set3")

Take a look at the following output screenshot: