::p_load(sf, tmap, tidyverse, rvest) pacman
2 Thematic Mapping and GeoVisualisation with R
2.1 Overview
In general, thematic mapping involves the use of map symbols to visualize selected properties of geographic features that are not naturally visible, such as population, temperature, crime rate, and property prices, just to mention a few of them.
Geovisualisation, on the other hand, is the process of using visual representations and cartographic techniques to explore, analyze, and communicate geospatial data. It combines elements of cartography, computer science, and information visualization to enhance spatial understanding and knowledge discovery.
In this chapter, you will learn how to plot functional and truthful choropleth maps by using an R package called tmap package.
2.1.1 Survival Tip
It is advisable for you to read the functional description of each function before using them.
2.2 Getting Started
In this hands-on exercise, the key R package use is tmap package in R. Beside tmap package, five other R packages will be used. They are:
- readr for importing delimited text file,
- tidyr for tidying data,
- dplyr for wrangling data and
- sf for handling geospatial data.
- rvest for scraping (or harvesting) data from web pages.
Among the five packages, readr, tidyr and dplyr are part of tidyverse package.
The code chunk below will be used to install and load these packages in RStudio.
Notice that, we only need to install tidyverse instead of readr, tidyr and dplyr individually.
2.3 Importing Data into R
2.3.1 The Data
Two data set will be used to create the choropleth map. They are:
Master Plan 2019 Subzone Boundary (No Sea) (KML). It can be downloaded at data.gov.sg This is a geospatial data. It consists of the geographical boundary of Singapore at the planning subzone level. The data is based on URA Master Plan 2019.
Singapore Residents by Planning Area / Subzone, Age Group, Sex and Type of Dwelling, June 2024 in csv format (i.e.
respopagesextod2024.csv
). This is an aspatial data fie. It can be downloaded at Department of Statistics, Singapore. Although it does not contain any coordinates values, but it’s PA and SZ fields can be used as unique identifiers to georeference to Master Plan 2019 Subzone Boundary.
2.3.2 Importing Geospatial Data into R
The code chunk below uses the st_read() function of sf package to import MP14_SUBZONE_WEB_PL
shapefile into R as a simple feature data frame called mpsz
.
<- st_read("chap02/data/geospatial/MasterPlan2019SubzoneBoundaryNoSeaKML.kml") mpsz
Reading layer `URA_MP19_SUBZONE_NO_SEA_PL' from data source
`C:\tskam\r4gdsa\chap02\data\geospatial\MasterPlan2019SubzoneBoundaryNoSeaKML.kml'
using driver `KML'
Simple feature collection with 332 features and 2 fields
Geometry type: MULTIPOLYGON
Dimension: XY, XYZ
Bounding box: xmin: 103.6057 ymin: 1.158699 xmax: 104.0885 ymax: 1.470775
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
2.3.2.1 Tidying data
Function to extract values from the HTML description
<- function(html_text, field_name) {
extract_kml_field if (is.na(html_text) || html_text == "") return(NA_character_)
<- read_html(html_text)
page <- page %>% html_elements("tr")
rows
<- rows %>%
value keep(~ html_text2(html_element(.x, "th")) == field_name) %>%
html_element("td") %>%
html_text2()
if (length(value) == 0) NA_character_ else value
}
<- mpsz %>%
mpsz mutate(
REGION_N = map_chr(Description, extract_kml_field, "REGION_N"),
PLN_AREA_N = map_chr(Description, extract_kml_field, "PLN_AREA_N"),
SUBZONE_N = map_chr(Description, extract_kml_field, "SUBZONE_N"),
SUBZONE_C = map_chr(Description, extract_kml_field, "SUBZONE_C")
%>%
) select(-Name, -Description) %>%
relocate(geometry, .after = last_col())
You can examine the content of mpsz
by using the code chunk below.
mpsz
Simple feature collection with 332 features and 4 fields
Geometry type: MULTIPOLYGON
Dimension: XY, XYZ
Bounding box: xmin: 103.6057 ymin: 1.158699 xmax: 104.0885 ymax: 1.470775
z_range: zmin: 0 zmax: 0
Geodetic CRS: WGS 84
First 10 features:
REGION_N PLN_AREA_N SUBZONE_N SUBZONE_C
1 CENTRAL REGION BUKIT MERAH DEPOT ROAD BMSZ12
2 CENTRAL REGION BUKIT MERAH BUKIT MERAH BMSZ02
3 CENTRAL REGION OUTRAM CHINATOWN OTSZ03
4 CENTRAL REGION DOWNTOWN CORE PHILLIP DTSZ04
5 CENTRAL REGION DOWNTOWN CORE RAFFLES PLACE DTSZ05
6 CENTRAL REGION OUTRAM CHINA SQUARE OTSZ04
7 CENTRAL REGION BUKIT MERAH TIONG BAHRU BMSZ10
8 CENTRAL REGION DOWNTOWN CORE BAYFRONT SUBZONE DTSZ12
9 CENTRAL REGION BUKIT MERAH TIONG BAHRU STATION BMSZ04
10 CENTRAL REGION DOWNTOWN CORE CLIFFORD PIER DTSZ06
geometry
1 MULTIPOLYGON Z (((103.8145 ...
2 MULTIPOLYGON Z (((103.8221 ...
3 MULTIPOLYGON Z (((103.8438 ...
4 MULTIPOLYGON Z (((103.8496 ...
5 MULTIPOLYGON Z (((103.8525 ...
6 MULTIPOLYGON Z (((103.8486 ...
7 MULTIPOLYGON Z (((103.8311 ...
8 MULTIPOLYGON Z (((103.8589 ...
9 MULTIPOLYGON Z (((103.8283 ...
10 MULTIPOLYGON Z (((103.8552 ...
Notice that only the first ten records will be displayed. Do you know why?
2.3.3 Importing Attribute Data into R
Next, we will import respopagesextod2024.csv file into RStudio and save the file into an tibble dataframe called popdata.
The task will be performed by using read_csv() function of readr package as shown in the code chunk below.
<- read_csv("chap02/data/aspatial/respopagesextod2024.csv") popdata
2.3.4 Data Preparation
Before a thematic map can be prepared, you are required to prepare a data table with year 2020 values. The data table should include the variables PA, SZ, YOUNG, ECONOMY ACTIVE, AGED, TOTAL, DEPENDENCY.
- YOUNG: age group 0 to 4 until age groyup 20 to 24,
- ECONOMY ACTIVE: age group 25-29 until age group 60-64,
- AGED: age group 65 and above,
- TOTAL: all age group, and
- DEPENDENCY: the ratio between young and aged against economy active group
2.3.4.1 Data wrangling
The following data wrangling and transformation functions will be used:
- pivot_wider() of tidyr package, and
- mutate(), filter(), group_by() and select() of dplyr package
<- popdata %>%
popdata2024 group_by(PA, SZ, AG) %>%
summarise(`POP` = sum(`Pop`)) %>%
ungroup()%>%
pivot_wider(names_from=AG,
values_from=POP) %>%
mutate(YOUNG = rowSums(.[3:6])
+rowSums(.[12])) %>%
mutate(`ECONOMY ACTIVE` = rowSums(.[7:11])+
rowSums(.[13:15]))%>%
mutate(`AGED`=rowSums(.[16:21])) %>%
mutate(`TOTAL`=rowSums(.[3:21])) %>%
mutate(`DEPENDENCY` = (`YOUNG` + `AGED`)
/`ECONOMY ACTIVE`) %>%
select(`PA`, `SZ`, `YOUNG`,
`ECONOMY ACTIVE`, `AGED`,
`TOTAL`, `DEPENDENCY`)
2.3.4.2 Joining the attribute data and geospatial data
Before we can perform the georelational join, one extra step is required to convert the values in PA and SZ fields to uppercase. This is because the values of PA and SZ fields are made up of upper- and lowercase. On the other, hand the SUBZONE_N and PLN_AREA_N are in uppercase.
<- popdata2024 %>%
popdata2024 mutate_at(.vars = vars(PA, SZ),
.funs = list(toupper)) %>%
filter(`ECONOMY ACTIVE` > 0)
Next, left_join() of dplyr is used to join the geographical data and attribute table using planning subzone name e.g. SUBZONE_N and SZ as the common identifier.
<- left_join(mpsz, popdata2024,
mpsz_pop2024 by = c("SUBZONE_N" = "SZ"))
Thing to learn from the code chunk above:
- left_join() of dplyr package is used with
mpsz
simple feature data frame as the left data table is to ensure that the output will be a simple features data frame.
write_rds(mpsz_pop2024, "chap02/data/rds/mpsz_pop2024.rds")
2.4 Choropleth Mapping Geospatial Data Using tmap
Choropleth mapping involves the symbolisation of enumeration units, such as countries, provinces, states, counties or census units, using area patterns or graduated colors. For example, a social scientist may need to use a choropleth map to portray the spatial distribution of aged population of Singapore by Master Plan 2014 Subzone Boundary.
Two approaches can be used to prepare thematic map using tmap, they are:
- Plotting a thematic map quickly by using qtm().
- Plotting highly customisable thematic map by using tmap elements.
2.4.1 Plotting a choropleth map quickly by using qtm()
The easiest and quickest to draw a choropleth map using tmap is using qtm(). It is concise and provides a good default visualisation in many cases.
The code chunk below will draw a cartographic standard choropleth map as shown below.
tmap_mode("plot")
qtm(shp = mpsz_pop2024,
fill = "DEPENDENCY")
Things to learn from the code chunk above:
- tmap_mode() with “plot” option is used to produce a static map. For interactive mode, “view” option should be used.
- fill argument is used to map the attribute (i.e. DEPENDENCY)
2.4.2 Creating a choropleth map by using tmap’s elements
Despite its usefulness of drawing a choropleth map quickly and easily, the disadvantge of qtm() is that it makes aesthetics of individual layers harder to control. To draw a high quality cartographic choropleth map as shown in the figure below, tmap’s drawing elements should be used.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5,
values = "brewer.blues"),
fill.legend = tm_legend(
title = "Dependency ratio")) +
tm_title("Distribution of Dependency Ratio by planning subzone") +
tm_layout(frame = TRUE) +
tm_borders(fill_alpha = 0.5) +
tm_compass(type="8star", size = 2) +
tm_scalebar() +
tm_grid(alpha =0.2) +
tm_credits("Source: Planning Sub-zone boundary from Urban Redevelopment Authorithy (URA)\n and Population data from Department of Statistics DOS",
position = c("left", "bottom"))
In the following sub-section, we will share with you tmap functions that used to plot these elements.
2.4.2.1 Drawing a base map
The basic building block of tmap is tm_shape()
followed by one or more layer elemments such as tm_polygons()
, tm_symbols()
, tm_lines()
, tm_raster()
and tm_text()
.
In the code chunk below, tm_shape()
is used to define the input data (i.e mpsz_pop2024) and tm_polygons()
is used to draw the planning subzone polygons
tm_shape(mpsz_pop2024) +
tm_polygons()
By default, it plots areas of polygons in light gray (gray85) and polygons borders in slightly dark gray (gray25).
2.4.2.2 Drawing a choropleth map using tm_polygons()
To draw a choropleth map showing the geographical distribution of a selected variable by planning subzone, we just need to assign the target variable such as Dependency to tm_polygons().
tm_shape(mpsz_pop2024)+
tm_polygons(fill = "DEPENDENCY")
Things to learn from tm_polygons():
- The default interval binning used to draw the choropleth map is called “pretty”. A detailed discussion of the data classification methods supported by tmap will be provided in sub-section 4.3.
- The default colour scheme used is
blues3
of ColorBrewer. You will learn more about the color scheme in sub-section 4.4. - By default, Missing value will be shaded in grey.
2.4.2.3 Drawing a choropleth map using tm_fill() and *tm_border()**
Actually, tm_polygons()
is a wraper of tm_fill()
and tm_border()
. tm_fill()
shades the polygons by using the default colour scheme and tm_borders()
adds the borders of the polygon features onto the choropleth map.
The code chunk below draws a choropleth map by using tm_fill()
alone.
tm_shape(mpsz_pop2024)+
tm_fill("DEPENDENCY")
Notice that the planning subzones are shared according to the respective dependecy values
To add the boundary of the planning subzones, tm_borders()
will be used as shown in the code chunk below.
tm_shape(mpsz_pop2024)+
tm_fill("DEPENDENCY") +
tm_borders()
Notice that light-gray border lines have been added on the choropleth map.
The fill_alpha
argument is used to define transparency number between 0 (totally transparent) and 1 (not transparent). By default, the alpha value of the col is used (normally 1).
Beside fill_alpha
argument, there are three other arguments for tm_borders()
, they are:
col
= border colour,lwd
= border line width. The default is 1, andlty
= border line type. The default is “solid”.
tm_shape(mpsz_pop2024)+
tm_fill("DEPENDENCY") +
tm_borders(col = "grey60",
lwd = 0.1,
lty = "dashed")
2.4.3 Data classification methods of tmap
Most choropleth maps employ some methods of data classification. The point of classification is to take a large number of observations and group them into data ranges or classes.
tmap provides a total ten data classification methods, namely: fixed, sd, equal, pretty (default), quantile, kmeans, hclust, bclust, fisher, and jenks.
To define a data classification method, the style argument of tm_fill() or tm_polygons() will be used.
2.4.3.1 Plotting choropleth maps with built-in classification methods
The code chunk below shows a quantile data classification that used 5 classes.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5)) +
tm_borders(fill_alpha = 0.5)
In the code chunk below, equal data classification method is used.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "equal",
n = 5)) +
tm_borders(fill_alpha = 0.5)
Notice that the distribution of quantile data classification method are more evenly distributed then equal data classification method.
Warning: Maps Lie!
DIY: Using what you had learned, prepare choropleth maps by using different classification methods supported by tmap and compare their differences.
DIY: Preparing choropleth maps by using similar classification method but with different numbers of classes (i.e. 2, 6, 10, 20). Compare the output maps, what observation can you draw?
2.4.3.2 Plotting choropleth map with custome break
For all the built-in styles, the category breaks are computed internally. In order to override these defaults, the breakpoints can be set explicitly by means of the breaks
argument to the tm_scale_intervals()
. It is important to note that, in tmap the breaks include a minimum and maximum. As a result, in order to end up with n categories, n+1 elements must be specified in the breaks
option (the values must be in increasing order).
Before we get started, it is always a good practice to get some descriptive statistics on the variable before setting the break points. Code chunk below will be used to compute and display the descriptive statistics of DEPENDENCY field.
summary(mpsz_pop2024$DEPENDENCY)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
0.1905 0.7450 0.8377 0.8738 0.9366 12.7500 94
With reference to the results above, we set break point at 0.60, 0.70, 0.80, and 0.90. In addition, we also need to include a minimum and maximum, which we set at 0 and 100. Our breaks
vector is thus c(0, 0.60, 0.70, 0.80, 0.90, 1.00)
Now, we will plot the choropleth map by using the code chunk below.
tm_shape(mpsz_pop2024)+
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
breaks = c(0, 0.60, 0.70, 0.80, 0.90, 1.00))) +
tm_borders(fill_alpha = 0.5)
2.4.4 Colour Scheme
tmap supports colour ramps either defined by the user or a set of predefined colour ramps from the RColorBrewer package.
2.4.4.1 Using ColourBrewer palette
To change the colour, we assign the preferred colour to palette argument of values as shown in the code chunk below.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5,
values = "brewer.greens")) +
tm_borders(fill_alpha = 0.5)
Notice that the choropleth map is shaded in green.
To reverse the colour shading, add a “-” prefix.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5,
values = "-brewer.greens")) +
tm_borders(fill_alpha = 0.5)
Notice that the colour scheme has been reversed.
2.4.4.2 Cartographic Furniture
Beside map style, tmap also also provides arguments to draw other map furniture such as compass, scale bar and grid lines.
In the code chunk below, tm_compass()
, tm_scale_bar()
, tm_grid()
and tm_credit()
are used to add compass, scale bar, grid lines and data sources onto the choropleth map.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5)) +
tm_borders(fill_alpha = 0.5) +
tm_compass(type="8star", size = 2) +
tm_scalebar() +
tm_grid(lwd = 0.1, alpha = 0.2) +
tm_credits("Source: data.gov.sg & singstat",
position = c("left", "bottom"))
2.4.5 Map Layout
Map layout refers to the combination of all map elements into a cohensive map. It includes the map background, frame, typography, scale, aspect ratio, margins, and more.
We can customize the map layout using the tm_layout()
function. In this section, we cover the most often used arguments of this function using the dependency choropleth map as example.
2.4.5.1 Map Legend
In tmap, several legend options are provided to change the placement, format and appearance of the legend.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5),
fill.legend = tm_legend(
title = "Dependency ratio")) +
tm_pos_auto_in() +
tm_borders(fill_alpha = 0.5) +
tm_compass(type="8star", size = 2) +
tm_scalebar() +
tm_grid(lwd = 0.1, alpha = 0.2) +
tm_credits("Source: data.gov.sg & singstat",
position = c("left", "bottom"))
2.4.5.2 Map style
tmap allows a wide variety of layout settings to be changed. They can be called by using tmap_style().
The code chunk below shows the classic style is used.
tm_shape(mpsz_pop2024) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
n = 5,
values = "-brewer.greens")) +
tm_borders(fill_alpha = 0.5) +
tmap_style("natural")
To reset the default style, refer to the code chunk below.
tmap_style("white")
2.5 Drawing Small Multiple Choropleth Maps
Small multiple maps, also referred to as facet maps, are composed of many maps arrange side-by-side, and sometimes stacked vertically. Small multiple maps enable the visualisation of how spatial relationships change with respect to another variable, such as time.
In tmap, small multiple maps can be plotted in three ways:
- by assigning multiple values to at least one of the asthetic arguments,
- by creating multiple stand-alone maps with tmap_arrange(), and
- by defining a group-by variable in tm_facets().
2.5.1 By assigning multiple values to at least one of the aesthetic arguments
In this example, small multiple choropleth maps are created by assigning two variables to the visual variable (i.e. fill).
tm_shape(mpsz_pop2024) +
tm_polygons(
fill = c("YOUNG", "AGED"),
fill.legend =
tm_legend(position = tm_pos_in(
"right", "bottom")),
fill.scale = tm_scale_intervals(
style = "equal",
n = 5,
values = "brewer.blues")) +
tm_borders(fill_alpha = 0.5) +
tmap_style("natural")
2.5.2 By arrange multiples choropleth maps in a grid layout
In this example, multiple choropleth maps are created and tmap_arrnage()
is used to arrnage them in a grid layout.
<- tm_shape(mpsz_pop2024)+
youngmap tm_polygons(fill = "YOUNG",
fill.legend = tm_legend(
position = tm_pos_in(
"right", "bottom"),
item.height = 0.8),
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.blues")) +
tm_borders(fill_alpha = 0.5) +
tm_title("Distribution of young population")
<- tm_shape(mpsz_pop2024)+
agedmap tm_polygons(fill = "AGED",
fill.legend = tm_legend(
position = tm_pos_in(
"right", "bottom"),
item.height = 0.8),
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.blues")) +
tm_borders(fill_alpha = 0.5) +
tm_title("Distribution of aged population")
tmap_arrange(youngmap, agedmap, asp=1, ncol=2)
2.5.3 By defining a group-by variable in tm_facets()
In this example, multiple small choropleth maps are created by using tm_facets().
tm_shape(mpsz_pop2024) +
tm_fill(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.blues")) +
tm_facets(by = "REGION_N",
nrow = 2,
ncols = 3,
free.coords=TRUE,
drop.units=TRUE) +
tm_layout(legend.show = TRUE,
title.position = c("center", "center"),
title.size = 20) +
tm_borders(fill_alpha = 0.5)
2.6 Mappping Spatial Object Meeting a Selection Criterion
Instead of creating small multiple choropleth map, you can also use filter()
of dplyr package to select geographical area of interest and plot a choropleth map focus only on the selected region.
%>%
mpsz_pop2024 filter(REGION_N == "CENTRAL REGION") %>%
tm_shape() +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.greens"),
fill.legend = tm_legend()) +
tm_borders(fill_alpha = 0.5)
2.7 Complementing Thematic Map with Statistical Chart
Maps and statistical charts complement each other by visually representing different aspects of the same data, offering a more comprehensive understanding. Maps excel at showing spatial relationships and geographical patterns, while charts effectively display numerical data, trends, and comparisons. Combining both allows for a more insightful and engaging data narrative, especially when dealing with spatial data that also has quantifiable characteristics.
With tmap, statistical chart and be incorporate into the map visualisation by using fill.chat
argument of map layers and legend chart feature as shown in the code chunk below.
%>%
mpsz_pop2024 filter(REGION_N == "CENTRAL REGION") %>%
tm_shape() +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.greens"),
fill.legend = tm_legend(),
fill.chart = tm_chart_box()) +
tm_borders() +
tm_layout(asp = 0.8)
In the code chunk below, We improve the visual representation further by highlighting and lebaling the outliers on the choropleth map.
<- mpsz_pop2024 %>%
mpsz_selected filter(REGION_N == "CENTRAL REGION")
<- boxplot.stats(mpsz_selected$DEPENDENCY)
stats
<- stats$out
outlier_vals
<- mpsz_selected[mpsz_selected$DEPENDENCY %in% outlier_vals, ]
outlier_sf
tm_shape(mpsz_selected) +
tm_polygons(fill = "DEPENDENCY",
fill.scale = tm_scale_intervals(
style = "quantile",
values = "brewer.blues"),
fill.legend = tm_legend(),
fill.chart = tm_chart_box()) +
tm_borders(fill_alpha = 0.5) +
tm_shape(outlier_sf) +
tm_borders(col = "red", lwd = 2) +
tm_text("SUBZONE_N", col = "red", size = 0.7) +
tm_layout(asp = 0.8)
2.8 Creating Interactive Map
Interactive maps let users actively explore and interact with the data they display. Unlike static maps, you can zoom in and out, pan across areas, click on locations for more information, and even work with data overlays or visualizations—making the experience more dynamic and informative. One of the great things about tmap is that it lets you switch easily between static and interactive maps using tmap_mode()
, so you can choose the view that best suits your analysis.
By modifying the code chunk in sub-section 2.6, the code chunks below build an interactive map using
<- mpsz_pop2024 %>%
region_selected filter(REGION_N == "CENTRAL REGION")
<- st_bbox(region_selected)
region_bbox
<- boxplot.stats(region_selected$DEPENDENCY)
stats <- stats$out
outlier_vals <- region_selected[region_selected$DEPENDENCY %in% outlier_vals, ]
outlier_sf
tmap_mode("view")
tm_shape(region_selected,
bbox = region_bbox) +
tm_fill("DEPENDENCY",
id = "SUBZONE_N",
popup.vars = c(
"Name" = "SUBZONE_N",
"Dependency" = "DEPENDENCY")) +
tm_borders() +
tm_shape(outlier_sf) +
tm_borders(col = "red", lwd = 2)
tmap_mode("plot")
The interactive map above is far from satisfactory. While we want to encourage users to engage and explore the interactive by zooming in and out of the study area freely. But, users might lost in the cyberspace with too much freedom to zoom-in and zoom-out.
To address this issue, set_zoom_limits
argument can be used to limit the map extend users can zooming in and out of the map areas as shown below.
<- mpsz_pop2024 %>%
region_selected filter(REGION_N == "CENTRAL REGION")
<- st_bbox(region_selected)
region_bbox
<- boxplot.stats(region_selected$DEPENDENCY)
stats <- stats$out
outlier_vals <- region_selected[region_selected$DEPENDENCY %in% outlier_vals, ]
outlier_sf
tmap_mode("view")
tm_shape(region_selected,
bbox = region_bbox) +
tm_fill("DEPENDENCY",
id = "SUBZONE_N",
popup.vars = c(
"Name" = "SUBZONE_N",
"Dependency" = "DEPENDENCY")) +
tm_borders() +
tm_shape(outlier_sf) +
tm_borders(col = "red", lwd = 2) +
tm_view(set_zoom_limits = c(12,14))
tmap_mode("plot")