Open In App

Making Maps with R

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are plenty of packages in R that can be used to make maps, like leaflet, tmap, mapview, maps, ggplot, spplot, etc. Each of the packages has its own advantages and disadvantages. But all of them have the common goal of making it easy to create maps and visualize geospatial data. To create a map with R, the first thing you need to have is data that includes geospatial information, such as latitude and longitude coordinates or shapefiles then from that you can use packages like rgdal to read and manipulate these data, and finally then use one of the mapping packages to visualize the data.

Another equally important notion in making maps with R is the usage of projections. A projection is a method to represent the earth’s surface on a flat map and there are many different projections that can be used for different purposes. Some projection preserves area or angles while others preserve distances or directions. While choosing a projection for a map it’s important to consider what aspect of the earth’s surface you want to emphasize or preserve.

Steps Required:

  1. Installing the required packages: You’ll need to install several of the packages to make maps with R, like leaflet and tmap. You can install a package by running the following code in the R console: install.packages(“package_name”).
  2. Loading packages: Once you installed the required packages then you’ll need to load them in your R session. You can do so by running the following code in the R console: library(package_name).
  3. Getting data: To make maps you’ll need geographic data such as a shapefile or a geojson file. You can find free geographic data online or on websites such as Natural Earth.
  4. Starting a new R script: Open RStudio and start a new R script where you’ll be writing the code to make the map.

Plotting Simple Features (sf) with Plot

We’ve used the “sf” and “RColorBrewer” libraries. what we did is first we loaded a shapefile “nc” which contains information on the counties in North Carolina and then demonstrated how to plot a simple feature using the “plot” function from the “sf” package. We specifically plotted the “AREA” attribute of the “nc” dataset, with a main title “AREA” and styled the plot with color palette using the “brewer.pal” function from the “RColorBrewer” library which generates a palette of 9 colors in a yellow-orange-red gradient (“YlOrRd”). Finally, plot is then divided into 9 bins using the “quantile” option in the “breaks” argument, and the palette is applied to color the bins with the “pal” argument.

R




library(sf)
library(RColorBrewer)
  
# Load data
nc <- st_read(system.file("shape/nc.shp", package="sf"))
  
# Plotting simple features (sf) with plot
plot(nc["AREA"], main = "AREA", breaks = "quantile",
     nbreaks = 9, pal = brewer.pal(9, "YlOrRd"))


Output:

 

Creating an Interactive Web Map with a leaflet

Here, we used the leaflet() function to initialize the map and added tile layers using addTiles() then added a marker with a popup label at the specific latitude and longitude of the “Patna City” using addMarkers(). And below is the result as an interactive map that can be zoomed in and out and have popups displayed on markers.

R




library(leaflet)
leaflet() %>% 
 addTiles() %>% 
 addMarkers(lng = 85.21, lat = 25.59, 
            popup = "Patna City")


Output:

 

Creating a Choropleth Map with ggplot2

In this example, the map_data function is used to retrieve the world map data that are then passed to ggplot to create the base plot. The fill color of polygon shapes that represent the countries is set to a solid gray color, and the outline color is set to a lighter gray color. The coord_map function is then used to set up a Mercator map projection and the ggtitle function is used to add a title to the plot. Finally, the theme_void function is used to remove the default plot background allowing the map to take center stage.

R




library(ggplot2)
library(maps)
world_map <- map_data("world")
ggplot(world_map, aes(long, lat, group = group)) + 
  geom_polygon(fill = "gray90", color = "gray50") + 
  coord_map("mercator") + 
  ggtitle("World Map") + 
  theme_void()


Output:

 

Creating a Choropleth Map with spplot

We’ve used the spplot function from the sp package to plot a choropleth map of North Carolina counties’ SID74 variable that represents the percentage of individuals with high school diplomas there. We first loaded nc shapefile using st_read function from the sf package and then used the spplot function to plot the map specifying the dataset and the variable to plot, and the color palette to use. Below is the resulting plot that shows the variation of the SID74 variable across the counties in North Carolina.

R




library(sp)
library(sf)
library(RColorBrewer)
  
# Load data
nc <- st_read(system.file("shape/nc.shp", package="sf"))
  
# Convert sf object to sp object
nc_sp <- as(nc, "Spatial")
  
# Create choropleth map with spplot
spplot(nc_sp, "SID74", main = "SID74", col.regions = brewer.pal(9, "YlOrRd"))


Output

 

Plotting Points on a Map with mapview

In the above code we first is we created a data frame with three points, each with longitude, latitude, and name, and then converted the data frame to spatial points data frame using st_as_sf() function. Then mapview() function is used to visualize the points on a map with the label argument used to display the names of the points.

R




library(mapview)
  
# Create example data of points
lng = c(85.21, 80.23, 77.28)
lat = c(25.59, 12.99, 28.56)
names = c("Patna", "Chennai", "New Delhi")
  
# Create a data frame with the point data
points_df = data.frame(lng, lat, names)
  
# Convert the data frame to a spatial points data frame
points_sdf = st_as_sf(points_df, 
                  coords = c("lng", "lat"), crs = 4326)
  
# Plot the points on a map
mapview(points_sdf, label = points_sdf$names)


Output:

 

Choropleth with tmap

In the above code, we’ve used tmap library to create a choropleth map of North Carolina’s BIR79 variable. Then, used sf library reads the shapefile data and tm_shape() function is used to create a tmap object of that shapefile, that’s then passed into the tm_polygons() function to make the choropleth map. Finally, the “quantile” style is used to classify the data. the title is used to add a title to the map.

C++




library(tmap)
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
tm_shape(nc) +
  tm_polygons("BIR79"
              style="quantile"
              title="NC BIR79")


Output:

 

Now we’ll use more functions in the above code example.

  • tmap_mode(“view”) which sets tmap mode to interactive. This means that plot will be displayed as an interactive map where user can zoom in and out and pan around and also hover over map elements to see their values.
  • tmap_last() that creates and displays the tmap plot as the final output.

R




tmap_mode("view")
tmap_last()


Output:

The output is an interactive map of North Carolina with a choropleth map of the BIR79 variable that represents the birth in North Carolina in the year 1979. We’ve divided the map into quantiles with a legend indicating the range of values for each quantile and also titled “NC BIR79”. The interactive features allow the user to explore the map in more detail, like clicking on different regions to see their exact values for the BIR79 variable.

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads