Map with ggplot2

Make beautiful maps with ggplot2
ggplot2
map
sf
dplyr
Author

MSH Mandal

Published

March 29, 2023

Divisons of Bangladesh

First load required packages

library(ggplot2)
library(geodata)
library(dplyr)
library(sf)

Get country vector file from GADM.org. We use gadm() function from geodata package. Here, to download a vector file we need to specify the country, level and path arguments. Read the function help document for more details

# help("gadm")
bd_level1 <-geodata::gadm(
    country = "Bangladesh", # the country name
    level = 1,              # The level of administrative subdivision requested
    path = tempdir()        # path to download
    )

The bd_level1 variable now contains our file. This is a vect class object native for the “terra” package. However, I prefer using the “sf” object for vector file types.

So, first using “st_as_sf()” lets convert it from terra “class” to “sf”

bd_sf <- bd_level1 %>% st_as_sf() # to simple feature (sf) types
# here using pipe ( %>% ) operator from dplyr package
# without pipe operator, we also could use it simply like below.

bd_sf <- st_as_sf(bd_level1) # this is equivalent to the previous code.

# but later we will use the pipe approach to write shorter 
# and easier to understand codes. But first let's check our data

head(bd_sf,2)  # check first few rows
Simple feature collection with 2 features and 11 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: 89.85194 ymin: 20.74111 xmax: 92.67366 ymax: 24.26797
Geodetic CRS:  WGS 84
    GID_1 GID_0    COUNTRY     NAME_1                        VARNAME_1
1 BGD.1_1   BGD Bangladesh    Barisal                        Bakerganj
2 BGD.2_1   BGD Bangladesh Chittagong Chattagram|Parbattya Chattagram|
  NL_NAME_1 TYPE_1 ENGTYPE_1 CC_1 HASC_1 ISO_1                       geometry
1      <NA> Bibhag  Division   10  BD.BA  <NA> MULTIPOLYGON (((90.77085 21...
2      <NA> Bibhag  Division   20  BD.CG  <NA> MULTIPOLYGON (((92.33417 20...

Next we use ggplot2 to make a map

ggplot()+
    # we specify the data inside geom_sf()
    # within the geom_sf, we specify "fill" variables to fill the polygons
    geom_sf(data = bd_sf,aes(fill=NAME_1))+
    # next line we using viridis color palettes for discrete types
    scale_fill_viridis_d(name="Divisions")+
    # specify the x,y axis namea as well as title
    labs(x="Longitude",y="Latitude",title="Bangladesh")+
    # next line not strictly necessary, as ggplot by deafult will use
    # "EPSG:4326" coordinate system for geom_sf() types geometry. 
    # But I like to specify it explicitely
    coord_sf(crs = "EPSG:4326")

To save this plot use “ggsave”

# Uncomment the following line to run the code
# ggsave("./bd_map.jpg",dpi = 300,width = 6,height = 6)