-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearch_index.json
1 lines (1 loc) · 102 KB
/
search_index.json
1
[["index.html", "The afrimapr book Welcome", " The afrimapr book The afrimapr team 2021-05-18 Welcome This is the in-progress book introducing map making in R using African data. We aim to make a first version available in mid 2021. It is part of the afrimapr project running in 2020-21. The book is compiled from this repository. We welcome contributions, please get in touch or submit a github issue. "],["preface.html", "Preface", " Preface [code in index.Rmd] In-progress chapters Intro : aims of this book 1 Step through a simple example of process of mapmaking 2 R recap - help ensure readers know foundations 3 Spatial data types focusing on examples 4 Visualising spatial data part 1 : sf, mapview, tmap 5 Shiny interactive map applications 6 Sources of data, what is open data 7 Join non-spatial data onto spatial 8 Raster manipulation, e.g. summarising data by areas 9 OpenStreetMap data, what they are and how to use 10 Creating and editing spatial data 11 Visualising spatial data part 2, more advanced techniques 12 Case study 1 : health facility locations 13 Case study 2 14 The version of the book you are currently reading was last updated at: Sys.time() ## [1] "2021-05-18 16:11:09 CEST" Continuous integration (built on GitHub) "],["intro.html", "Chapter 1 Introduction 1.1 Why read this book 1.2 Who for 1.3 What this book will not cover 1.4 How the book is organised 1.5 Book formatting", " Chapter 1 Introduction [andy: we may move this text to the Preface later (coded in index.Rmd), but is more difficult to find there.] 1.1 Why read this book [mention reproducibility, html, markdown, QGIS etc.] 1.2 Who for The book is aimed principally at analysts who want to make maps from African data as a part of their routine work. We expect that readers will have had some limited experience of R and/or spatial data but this is not strictly required. We will take you step-by-step through code to obtain, manipulate and visualise spatial data. We focus on routine tasks and developing confidence and resilience in applying them, rather than moving to more advanced analyses. 1.3 What this book will not cover For those that are interested in spatial analyses we refer you to the excellent recent book Geocomputation with R. The afrimapr book, in comparison, will cover fewer processes but do so in more detail and assuming less prior knowledge of R and spatial data. We see the two books as being complementary. Those that wish to take their work further after this afrimapr book should find the geocompr book useful. Those that have been through the geocompr book and would like more detail on visualising varied data sources in R should find this afrimapr book useful. 1.4 How the book is organised [recap, taster chapters etc.] 1.5 Book formatting [exercise blocks, learning objectives etc.] "],["taster.html", "Chapter 2 A taster - making your first map 2.1 A simple map 2.2 Map components 2.3 Static maps 2.4 Interactive maps", " Chapter 2 A taster - making your first map This chapter shows the steps through an example process of map-making. It demonstrates the focus and potential of this book, so that the readers can quickly see what this book aims to achieve and how it is done. 2.1 A simple map tm_shape(africountries) + tm_polygons() 2.2 Map components In the example below, africountries is a dataset used to create a map. tm_polygons function is used to draw polygons of the map, col fills polygons based on the variable in the dataset, while title argument sets the legend title. tm_shape(africountries) + tm_polygons(col = "pop_est", title = "Population") 2.3 Static maps #Create an empty map of Africa using a classic style map_basic = tm_style("classic")+ tm_shape(africa)+ tm_polygons()+ tm_layout(title = "Africa", title.position = c("center", "top"), inner.margins = 0.05, legend.text.size = 0.47) #Add points for medium airports data(afriairports) m_airports = afriairports %>% filter(type == "medium_airport") map_points = map_basic + tm_shape(m_airports)+ tm_dots(col = "type", palette="blue", labels = "Medium airports", title = "")+ tm_legend(legend.position = c("left", "bottom")) + tm_layout(scale = 1.07) #Add bubbles with population and GDP size map_bubbles = map_points + tm_shape(africa)+ tm_bubbles(size = "pop_est", col = "income_grp", title.col = "Income level", title.size = "Population", labels = c("High", "Upper middle", "Lower middle", "Lower")) tmap_arrange(map_basic, map_points, map_bubbles) Figure 2.1: Examples of maps #Basic map 2 map_basic_2 = tm_style("watercolor")+ tm_shape(africa)+ tm_fill(col = "pop_est", style = "jenks", title = "Population")+ tm_layout(title = "Africa", title.position = c("center", "top"), legend.text.size = 0.50) #Add highways names map_highways = map_basic_2 + tm_shape(afrihighway)+ tm_lines(col = "black") #Add country names map_named = map_highways + tm_shape(africapitals)+ tm_dots(col = "red", border.col = "black")+ tm_text("capitalname", size = 0.35) tmap_arrange(map_basic_2, map_highways, map_named) Figure 2.2: Examples of maps 2 2.4 Interactive maps tmap_mode("view") ## tmap mode set to interactive viewing breaks=c(0,2,20,200,2000,25000) tm_shape(afripop2020) + tm_raster(breaks=breaks, title = "Population per km sq") + tm_shape(afrihighway) + tm_lines(col = "blue") + tm_shape(africapitals) + tm_dots(col = "black", alpha=0.5) "],["rrecap.html", "Chapter 3 R recap 3.1 Setting working directory 3.2 Creating, naming and saving a new R script 3.3 Executing the code 3.4 Install and load packages 3.5 Load data 3.6 Basic data types 3.7 Basic objects and data structures 3.8 Getting help with R Help 3.9 Further resources 3.10 Summary 3.11 Exercise solutions", " Chapter 3 R recap Previous section demonstrated what can be achieved with the learning materials provided in this book and gave an example of capabilities of packages that are used. This section presents basic steps that are required (or simply good practice) before starting the project. It provides a brief recap of R fundamentals such as data types and structures, objects and commands. It aims at building a starting point for those who are new to R and provide background knowledge that the reader can build on, while progressing through the further chapters of this book. It will be particularly useful for beginners, who have minimal knowledge of R. Therefore, more advanced readers can move forward to the next chapter where spatial data types are looked into. div.green { background-color:#e3ffd9; border-radius: 5px; padding: 20px;} Learning objectives Create a new R project and start working with data Identify and characterise different data types and structures in R Access and search for help within R List of episodes Working directory New script Executing code Install packages Load data Basic data types Basic objects Getting help 3.1 Setting working directory At the beginning of each project it is crucial to determine the working directory of your project. A working directory is a folder where all your files associated with the project will be stored. For example, original data sets, saved data sets as well as plots, graphs or maps created and exported from R. Hence, working directory not only allows you to gather and access the files produced along the work but also load the existing data sets into the RStudio. You can set up the working directory with the openProject function as follows (recommended): rstudioapi::openProject("path to your directory") Alternatively, you can use the following command: setwd("path to your directory") While the former option will set up and open the working directory for your project, the latter simply determines the default folder for each specific R script. 3.2 Creating, naming and saving a new R script The R script is a plain text file that allows you to save the R code containing both commands and comments. Saving the R script allows you to reuse your R code and creates a reproducible record of your work. Therefore, it is good practice to create, name and save it at the very beginning of your project. You can create a new R script by clicking the New File icon in the top right corner of the RStudio toolbar, which will open a list with different file options. Choose the R Script from the menu and the blank script will open in the main RStudio window. div.yellow { background-color:#fff5e6; border-radius: 5px; padding: 20px;} Shortcut: New R script can also be opened by Shift+Ctrl+N. You can now save your R script by clicking on the Save icon at the top of the Script Editor, this will prompt a Save File window where you can change the name of your script. Note that the file extension for R scripts is .R. At this point you can also choose a folder where to save your new file. By default, RStudio will try to save your new script in the current working directory. Once the name and file location are chosen, simply click the Save button. div.yellow { background-color:#fff5e6; border-radius: 5px; padding: 20px;} Shortcut: As you work along your R script document, you can quickly save changes by pressing Ctrl+S. 3.3 Executing the code Now that you have set up the working directory for your project and created your first R script file, we will look into ways of executing (also known as running) the code. You can execute selected chunk of code by clicking the Run button at the top right corner of the Script Editor. div.yellow { background-color:#fff5e6; border-radius: 5px; padding: 20px;} Shortcut: You can also execute the selected code with Ctrl+Enter. If you do not select any code and press Run, RStudio will run the line of code where the cursor is located. The code which has been exectued will appear in the Console, usually located at the bottom part of the window. In RStudio it is also possible to add comments next to your commands simply using a hashtag (#) beforehand. This will stop R from executing this specific part: 3+6 # Using R as a calculator ## [1] 9 # 3+6 This is also a convenient way to describe your R script, name different section and keep it organised. Short, descriptive headings will help you tidy up your work and will be helpful when remembering what each section does. Figure 3.1: An example of an organised and annotated R script 3.4 Install and load packages As described by Wickham & Bryan (2015) R package is basic unit of shareable code containing a collection of functions (and sometimes also datasets). One of the most popular and larges packages repository is Comprehensive R Archive Network (CRAN), but there are number of remote repositories, where packages can be published and stored by their authors such as Github or GitLab. Packages can differ in their capabilities and they will usually have a specific purpose, for example, data wrangling, visualisations or modelling. To learn more about a particular package we can use packageDescription, which calls a file with description of a package or help function that contains description of functions included in the package. For example, remotes package is often used to install other packages available at remote repositories. packageDescription("remotes") ## Package: remotes ## Title: R Package Installation from Remote Repositories, Including 'GitHub' ## Version: 2.3.0 ## Authors@R: c( person("Jim", "Hester", , "[email protected]", role = c("aut", "cre")), person("Gábor", "Csárdi", , ## "[email protected]", role = c("aut")), person("Hadley", "Wickham", role = c("aut")), person("Winston", ## "Chang", role = "aut"), person("RStudio", role = "cph"), person("Martin", "Morgan", role = "aut"), ## person("Dan", "Tenenbaum", role = "aut"), person("Mango Solutions", role = "cph") ) ## Description: Download and install R packages stored in 'GitHub', 'GitLab', 'Bitbucket', 'Bioconductor', or plain ## 'subversion' or 'git' repositories. This package provides the 'install_*' functions in 'devtools'. Indeed ## most of the code was copied over from 'devtools'. ## License: GPL (>= 2) ## URL: https://remotes.r-lib.org, https://github.com/r-lib/remotes#readme ## BugReports: https://github.com/r-lib/remotes/issues ## Imports: methods, stats, tools, utils ## Suggests: brew, callr, codetools, curl, covr, git2r (>= 0.23.0), knitr, mockery, pkgbuild (>= 1.0.1), pingr, rmarkdown, ## rprojroot, testthat, webfakes, withr ## Depends: R (>= 3.0.0) ## VignetteBuilder: knitr ## RoxygenNote: 7.1.1 ## SystemRequirements: Subversion for install_svn, git for install_git ## Encoding: UTF-8 ## NeedsCompilation: no ## Packaged: 2021-04-01 14:52:52 UTC; jhester ## Author: Jim Hester [aut, cre], Gábor Csárdi [aut], Hadley Wickham [aut], Winston Chang [aut], RStudio [cph], Martin ## Morgan [aut], Dan Tenenbaum [aut], Mango Solutions [cph] ## Maintainer: Jim Hester <[email protected]> ## Repository: CRAN ## Date/Publication: 2021-04-01 16:50:06 UTC ## Built: R 4.0.5; ; 2021-05-02 17:00:01 UTC; windows ## ## -- File: C:/Users/User/OneDrive - University of Leeds/Documents/R/win-library/4.0/remotes/Meta/package.rds help(package = "remotes") Before being able to use a specific package in R, it is necessary to first install and then load it. In this example we install package remotes using install.packages(). install.packages("remotes") Further, we have to load the package into R using library() function. Note the presence of the quotation mark (\"\") in case of the first function and its lack in case of the second function. library(remotes) As mentioned above, to download and install packages directly from remote repositories such as GitHub, we can use previously loaded remotes package and load them as usual: remotes::install_github("afrimapr/afrilearndata") library(afrilearndata) In the example above, we use double-colon operator :: to call function install_github from name spaceremotes. Only functions included in the packages can be retrieved in this manner. 3.5 Load data There are different approaches that can be used to import your data sets, depending on where the data is located and in what file type it is stored. The easiest case is when the data set is already part of the R package, as it will be automatically read in when the package is installed and loaded into R. For example, install and load packages containing data sets: remotes::install_github("afrimapr/afrilearndata") library(afrilearndata) To view what data sets are available in a given package: data(package="afrilearndata") We can view and explore the africapitals data set using: head(africapitals) ## Simple feature collection with 6 features and 4 fields ## Geometry type: POINT ## Dimension: XY ## Bounding box: xmin: -0.2 ymin: -18.89 xmax: 47.51 ymax: 36.77 ## Geodetic CRS: WGS 84 ## capitalname countryname pop iso3c geometry ## 280 Abuja Nigeria 178462 NGA POINT (7.17 9.18) ## 308 Accra Ghana 2029143 GHA POINT (-0.2 5.56) ## 382 Addis Abeba Ethiopia 2823167 ETH POINT (38.74 9.03) ## 996 Algiers Algeria 2029936 DZA POINT (3.04 36.77) ## 1584 Antananarivo Madagascar 1463754 MDG POINT (47.51 -18.89) ## 2193 Asmara Eritrea 578860 ERI POINT (38.94 15.33) We can also create a dataframe from africapitals in the global environment: dataset <- africapitals 3.6 Basic data types In this section we explore a basic set of possible object types that you can encounter in a dataframe. The division presented below is based on the types of values that data (object) stores. The most popular data types are: Numeric Character Logical (so-called Boolean) Factor In R the type of object is referred to as class of an object and this function can be used to learn what data types the object contains. x <- 11 #we create a vector that stores value 11 class(x) ## [1] "numeric" It is useful to check the class of an object because each class has different properties and can be used in a different way. For example, intuitively we can perform the mathematical operations on numeric objects such that: x <- 11 y <- 52 x*y # multiplication ## [1] 572 Hint: To assign a value to an object two operators can be used interchangeably: <- or =. 3.6.1 Numeric and integer Numeric data stores real numbers. This means that the object x from above is in fact 11.000000, where the zeros are not printed, by default. It is also possible to store value as whole number in a class object called integer. An integer can be created from a numeric object in the following way: x <- 13.5 z <- as.integer(x) class(z) ## [1] "integer" Please note, even though the numeric value is a decimal number the integer by default rounds downwards, hence both 13.1 and 13.9 will result in integer equal 13. 3.6.2 Characters Character objects store text, usually referred to as a string. String can be a letter, word or even a sentence. x <- "adult" y <- "A" y <- "I have a bicycle." Interestingly, a character can also contain a number, however it will be stored as a text and will not have the same properties as a numeric or integer object. As a results, it will not be possible to perform calculation on character objects, even if they contain numbers. This is when the class function becomes helpful. x <- "5" y <- 7 class(x) ## [1] "character" class(y) ## [1] "numeric" It is also possible to convert character variables into numeric: x <- "5" z <- as.numeric(x) class(z) ## [1] "numeric" 3.6.3 Logical Logical objects can take values TRUE or FALSE, where TRUE is an equivalent of 1 whereas FALSE is an equivalent of 0. In these sense, they can be thought of as numerical values. x <- TRUE y <- 3 + TRUE print(y) ## [1] 4 Typically, logical objects are results of a condition. For example, if we want to test if object a is larger than 100. a <- 76 #create object a a > 100 # condition 1 ## [1] FALSE a < 80 # condition 2 ## [1] TRUE 3.6.4 Factors Factors are categorical variables with associated levels. They can store both, numbers: a <- rep(1:3, times=3) # create a vector of numbers from 1 to 3, repeated 3 times a <- as.factor(a) a ## [1] 1 2 3 1 2 3 1 2 3 ## Levels: 1 2 3 and strings: b <- c("A", "B", "B", "C", "D", "C", "C") b <- as.factor(b) b ## [1] A B B C D C C ## Levels: A B C D The numbers and strings, in the example above, serve as labels of different levels. 3.6.5 Exercises div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 3.6.1: Create a vector a that contains descending sequence of numbers from 50 to 30 that decreases by 2. Hint: use seq() 3.7 Basic objects and data structures In this section we explain the basic data structures that we often work with in R. These include a vector, list, matrix and a data frame. 3.7.1 Vector Vector is a one dimensional structure which contains elements of the same type. Usually a combine function is used to create a vector such that: a <- c(1:10) It is also possible to create a vector with text-based objects, for example with capitals from our afrilearndata: capitals <- africapitals$capitalname We can print content of our vector to see what it contains: print(capitals) ## [1] "Abuja" "Accra" "Addis Abeba" "Algiers" "Antananarivo" "Asmara" "Bamako" "Bangui" ## [9] "Banjul" "Bissau" "Brazzaville" "Bujumbura" "Cairo" "Conakry" "Dakar" "Dodoma" ## [17] "Freetown" "Gaborone" "Harare" "Jibuti" "Kampala" "Khartoum" "Kigali" "Kinshasa" ## [25] "Libreville" "Lilongwe" "Lome" "Luanda" "Lusaka" "Malabo" "Maputo" "Maseru" ## [33] "Mbabane" "Mogadishu" "Monrovia" "N'Djamena" "Nairobi" "Niamey" "Nouakchott" "Ouagadougou" ## [41] "Porto Novo" "Pretoria" "Rabat" "Tripoli" "Tunis" "Windhoek" "Yamoussoukro" "Yaounde" ## [49] "al-'Ayun" "Juba" Another important feature is to see what types of objects the vector stores. We can see that our text-based objects are characters using typeof function: typeof(capitals) ## [1] "character" 3.7.2 Matrix Matrix can be thought of as an upgraded version of a vector, where vector is an one-dimensional array and the matrix is a two-dimensional array. We can create a matrix that has three columns and five rows with the following: matrix(1:15, ncol=3, nrow=5, byrow = TRUE) ## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 4 5 6 ## [3,] 7 8 9 ## [4,] 10 11 12 ## [5,] 13 14 15 By default, the elements in the matrix will be arranged by column, so byrow=TRUE segregates the elements in the matrix row-wise. We can also exploit the fact that matrix is an upgraded vector by binding them column- or row-wise, as long as they have the same length: vector1 <- c("water", "milk", "juice") vector2 <- (1:3) cbind(vector1, vector2) #for row-wise binding we would use rbind() ## vector1 vector2 ## [1,] "water" "1" ## [2,] "milk" "2" ## [3,] "juice" "3" 3.7.3 Data frame Data frame is a two dimensional array, similar to a matrix. However, unlike a matrix, it can contain different data types. In a data frame a column is a variable and row is an observation. You can create a simple data frame with two columns and three rows, using vectors above, with data.frame function: data.frame(vector1, vector2) ## vector1 vector2 ## 1 water 1 ## 2 milk 2 ## 3 juice 3 If you compare the output of the example above where we used the cbind function to create a matrix, to the result of the data.frame function, we can clearly see the difference between a matrix and a data frame. Where matrix is homogeneous and data frame is heterogeneous in terms of data type. All the values in the matrix are characters while the first column in data frame contains factors and the second one integers. To address a specific column in a data frame we can use $ such that: df_1 = data.frame(vector1, vector2) #create data frame called df_1 df_1$vector1 #view column called vector1 ## [1] "water" "milk" "juice" Columns in the df_1 have adapted names of the vectors: colnames(df_1) ## [1] "vector1" "vector2" We can change the column headers by their names or their index such that: names(df_1)[names(df_1) == "vector1"] <- "drinks" names(df_1)[2] <- "amount" colnames(df_1) ## [1] "drinks" "amount" 3.7.4 Exercises div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 3.7.1: Create three vectors containing character, integer and logical values, respectively. Each with 10 rows. Bind them to generate a matrix with 3 columns and 10 rows. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 3.7.2: Create a data frame from the matrix created in the previous exercise. Rename column headers to describe their content. 3.8 Getting help with R Help R is a powerful software with many different packages and functions which are continuously developed and added. Therefore, it is difficult, if not impossible, to be familiar with all the functions that are currently available. Hence, in order to learn more about them, R provides extensive documentation which can be accessed with help() function, ? operator or by clicking in Help panel in the bottom-right corner. For example: help(matrix) #to find out what matrix is help(package="remotes") #to get help with remotes package Alternatively, it is possible to use ? in front of the searched item and the R documentation will appear in right-bottom pane. For example, to read more on how to use help function itself we can use: ?help Importantly, in order to get help regarding objects with unusual names such as the logical operators, it is necessary to use quotation marks: ?"&" help("!") R documentation for functions frequently offers a working example which can be accessed with: #[andy commented out because seems to be causing error] #example(vector) #to see an example of a vector 3.9 Further resources Finally, the Internet also provides several reliable sources such as official R website, documentation pages, R packages book or knowledge sharing platform Stackoverflow where you can find help. 3.10 Summary In this chapter we learned several R commands which prepared the reader for starting with his/her own project. Moreover, we familiarised with a number of data types and R objects. Moreover, we looked at how to obtain help and access R documentation. The material covered in this section aimed at building a base for the reader to allow him/her successfully progress through the book. 3.11 Exercise solutions Exercise 3.6.1 a <- seq(50,30, by = -2) Exercise 3.7.1 v1 <- c("water", "milk", "juice", "coffee", "tea", "tea", "juice", "milk", "water", "soda") v2 <- seq(1,10) v3 <- rep(c(TRUE,FALSE), length.out = 10) v3 <-as.logical(v3) m1 = cbind(v1, v2, v3) m1 ## v1 v2 v3 ## [1,] "water" "1" "TRUE" ## [2,] "milk" "2" "FALSE" ## [3,] "juice" "3" "TRUE" ## [4,] "coffee" "4" "FALSE" ## [5,] "tea" "5" "TRUE" ## [6,] "tea" "6" "FALSE" ## [7,] "juice" "7" "TRUE" ## [8,] "milk" "8" "FALSE" ## [9,] "water" "9" "TRUE" ## [10,] "soda" "10" "FALSE" Exercise 3.7.2 df = data.frame(m1) names(df)[1] <- "Drink" names(df)[2] <- "Amount" names(df)[3] <- "Female" df$Female <-as.logical(df$Female) df$Amount <-as.integer(df$Amount) df ## Drink Amount Female ## 1 water 1 TRUE ## 2 milk 2 FALSE ## 3 juice 3 TRUE ## 4 coffee 4 FALSE ## 5 tea 5 TRUE ## 6 tea 6 FALSE ## 7 juice 7 TRUE ## 8 milk 8 FALSE ## 9 water 9 TRUE ## 10 soda 10 FALSE "],["data-types.html", "Chapter 4 Spatial data in R 4.1 Points 4.2 Lines 4.3 Polygons 4.4 Rasters 4.5 Further resources 4.6 Summary/key points", " Chapter 4 Spatial data in R The previous chapter provided a short recap of the R basics that will help you progress through this book. This chapter will focus on the fundamentals of mapping, i.e. the different types of data that can be used to make a map. This chapter is written for those with some knowledge of R and little experience with spatial data. If you are familiar with the different data types (points, lines, polygons and vectors), you may move on to the next chapter where visualisation of data types is explained in more detail. However you never know, you may learn something here too. div.green { background-color:#e3ffd9; border-radius: 5px; padding: 20px;} Learning objectives [andy: still thinking how best to structure these] Be able to describe and use points, lines, polygons and raster data types Understand the difference between vector and raster data Be able to read in data of the 4 types into R from files and other sources Know that the current best packages for manipulating spatial data are package sf for vector and package raster for raster. Be comfortable visualising the four different spatial data types in R using packages mapview & raster Maps are used for a wide range of purposes. In this book we focus on using maps to present data. A map can provide a model of reality to help the reader see where things or events are located. This could be on the scale of a street, a neighbourhood, a country or a continent. Depending on the topics youre interested in, this could be focussed on disease cases, landcover dynamics, location of schools. The opportunities are endless. The data that we can represent on a map can be divided into four main types : points lines polygons rasters Points can be used to represent the locations of e.g. cities, buildings, disease cases, sample sites or wildlife records. They can be used to represent the centre of an area. Points can be chosen when the shape of the location is not important. Thus for a map representing a continent, cities can be represented by points because the area of cities would not be visible. Lines may represent physical features such as rivers or roads, or routes travelled, or abstract links between point locations. [andy to continue ] All spatial data types require a coordinate reference system (CRS) identification to place data in the correct location on the earth. We will discuss this in more detail later. For now, just be aware that a code may need to be entered to ensure that data display in the correct place. Note also that spatial data types can be stored in many different formats, from Shapefile (.shp + .dbf + .prj + ), to GeoPackage (.gpkg), to CSV files (.csv). This can be overwhelming at times. Dont worry we will come to these later [Andy great if we can specify exactly where this information can be found]. List of episodes Points (cities) Lines (roads) Polygons (country boundaries) Rasters (population density) 4.1 Points Lets take an imaginary walk outside. What do you see? Houses, cars, trees All these objects have unique coordinates that can be used to identify their exact location. On a map, the objects can be drawn as points with their latitude and longitude coordinate indicating their exact location in relation to other objects and places. Depending on the scale of your map, points can represent anything from a house, health clinic, city or district. You, as the map creator, can decide the scale of your own map. 4.1.1 Example Lets try and visualise the capital cities of Africa which we have stored in the afrilearndata package. Just a quick reminder of the necessary packages library(afrilearndata) #load afrilearndata package #In case the data isn't loaded into your R environment automatically, it can be loaded individually using the code below. data(africapitals) #location of the African capitals We will start by downloading the necessary packages: sf package. This package is necessary to read in the spatial data files. tmap package. This package is necessary to create the maps. #install.packages("sf") #install sf package #install.packages("tmap") #install tmap package library(sf) #load sf package library(tmap) #load tmap package Note More information can be found about the different packages using the Help tools. Now, lets look at the data file that contains information about the African capitals. A quick summary of the spatial aspects (geometry) of the datafile can be checked using the following code: print(st_geometry(africapitals)) #printing information on the geometry ## Geometry set for 50 features ## Geometry type: POINT ## Dimension: XY ## Bounding box: xmin: -17.48 ymin: -29.31 xmax: 47.51 ymax: 36.84 ## Geodetic CRS: WGS 84 ## First 5 geometries: We can see from the results that the African capital data file contains 50 points (capitals) with geometry type POINT. Lets print the first 6 rows of data, so we can see how the coordinates of each African captial is stored in the database. head(africapitals) #First 6 rows of data are printed ## Simple feature collection with 6 features and 4 fields ## Geometry type: POINT ## Dimension: XY ## Bounding box: xmin: -0.2 ymin: -18.89 xmax: 47.51 ymax: 36.77 ## Geodetic CRS: WGS 84 ## capitalname countryname pop iso3c geometry ## 280 Abuja Nigeria 178462 NGA POINT (7.17 9.18) ## 308 Accra Ghana 2029143 GHA POINT (-0.2 5.56) ## 382 Addis Abeba Ethiopia 2823167 ETH POINT (38.74 9.03) ## 996 Algiers Algeria 2029936 DZA POINT (3.04 36.77) ## 1584 Antananarivo Madagascar 1463754 MDG POINT (47.51 -18.89) ## 2193 Asmara Eritrea 578860 ERI POINT (38.94 15.33) The capitals all have one latitude and one longitude value. The geometry of the point data is stored as POINT (Latitude, Longitude). On the location where the latitude and longitude overlap, a point will be drawn when POINT data is visualised. There is also another column that contains the population of the capital. Lets now visualise the African capitals by plotting their geometry using the tmap package. tm_shape(africapitals) + #specify the data file tm_dots() # displaying the point geometry The tmap package works similar to the ggplot package. You need to first specify the data file you want to visualise using tm_shape(), after which the exact format of the spatial data can be specified (points, lines, polygons). As we are working with point data in this example, the tm_dots() function is used. As with ggplot, there is a lot of flexibility in the colouring, shapes and sizes of the dots. For example, the dots can be turned red and labelled with the name of the city. tm_shape(africapitals) + tm_dots("red")+ # displaying the point geometry as red dots tm_text("capitalname", size=0.7 ) #adding the name As you can see in the example above, the labelling makes the image messy. In these instances it is important to think about the message you are trying to convey with your map. If the labelling is essential, you can look up the help section of the tm_text using the help tool and play around with the different options to clean up the map further. 4.1.2 Exercises div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 1 In this first exercise, we will use the same African capital data as our example. Below, We have visualised all capitals with > 1.400.000 people using green squares of size 1. However, the code isnt working. Can you find the four mistakes? Hint: if you get stuck, look at ?tm_dots #africapitals_filtered=africapitals %>% # dplyr::filter((africapitals$iso3c) > 1.400.000) #tm_shape(africapitals_filtered) + # tm_dots("green", size=0.5) Answer: * In the initial filter, africapitals$iso3c needs to be changed to africapitals$pop * Dots in 1.400.000 need to be removed * The shape of the dots need to be specified as squares using shape=22 * The size of the points needs to be 1. africapitals_filtered=africapitals %>% dplyr::filter((africapitals$pop) > 1400000) tm_shape(africapitals_filtered) + tm_dots("green", shape = 22, size=1) div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.1.2.1 Exercise 2 We will now use capital and African airport data. Visualise the capitals and airports in one map, with capitals as grey large filled-in circles and airports as smaller blue not-filled triangles. Hint: if you get stuck, look at Add Points to a Plot in the help section. Hint: When both points and lines are mapped, datasets need to be identified seperately in tm_shape() before the use of tm_dots(). Answer: tm_shape(africapitals) + tm_dots(col="grey", shape = 19, size=3) + tm_shape(afriairports) + tm_dots(col="blue", shape = 2, size=1) 4.2 Lines In previous episode we looked at point data, such as capitals and airports. We are often interested in how these different locations on a map are connect to eachother. These connections are visualised using lines. Roads, rivers and flight pathes are just a few of the many ways that lines are used. Lines are one dimensional data which are drawn using points (and thus point data) connected to eachother in a set order. Depending on the detail of the lines, more or less point data are connected. 4.2.1 Example For this example, we will look at the trans-African highway network. Lets start by looking at a quick summary of the spatial aspects (geometry). print(st_geometry(afrihighway)) #printing information on the geometry ## Geometry set for 100 features ## Geometry type: LINESTRING ## Dimension: XYZ ## Bounding box: xmin: -17.38929 ymin: -33.95247 xmax: 43.13781 ymax: 37.08586 ## z_range: zmin: 0 zmax: 0 ## Geodetic CRS: WGS 84 ## First 5 geometries: The results show that the African highway network contains 100 lines with geometry type LINESTRING. Lets now print the first 6 rows of data to see how line data are stored. head(afrihighway) #First 6 rows of data are printed ## Simple feature collection with 6 features and 1 field ## Geometry type: LINESTRING ## Dimension: XYZ ## Bounding box: xmin: -17.36938 ymin: 14.76957 xmax: -6.800537 ymax: 33.98436 ## z_range: zmin: 0 zmax: 0 ## Geodetic CRS: WGS 84 ## # A tibble: 6 x 2 ## Name geometry ## <chr> <LINESTRING [°]> ## 1 Western Sahara (Morocco) Link Z (-16.94778 21.34438 0, -16.85303 21.96343 0, -16.54541 22.12636 0, -16.32568 22.7457... ## 2 Mauritania Border- Dakar Link Z (-17.36938 14.76957 0, -16.9519 14.77488 0, -16.73218 14.97663 0, -16.22681 15.58071... ## 3 Nouakchott- Senegal Border Link Z (-15.81069 16.52036 0, -16.11694 16.72039 0, -16.10596 17.22476 0, -15.99609 17.6649... ## 4 Western Sahara Border- Nouakchott Link Z (-15.99128 18.08646 0, -16.01807 18.49003 0, -16.17188 18.84391 0, -16.16089 19.0932... ## 5 Marrakesh- Western Sahara (Morocco) Link Z (-12.95837 27.67623 0, -12.7002 28.0041 0, -12.12891 28.06229 0, -11.45874 28.31405 ... ## 6 Rabat- Marrakesh Link Z (-8.12439 31.79238 0, -8.02002 31.8589 0, -7.915649 32.50976 0, -7.767334 32.67175 0... Line data contain a string of data points with latitude and longitude: LINESTRING(Latitude1, Longitude1, Latitude2, Longitude2, Latitude3, Longitude3,.. ). During mapping, these points are connected to form a line. Lets visualise these linestrings in red by plotting their geometry using the tmap package. tm_shape(afrihighway) + tm_lines("red") Similar to point data, the lines can be illustrated in a large variety of ways. Please check the tm_lines() help section to familiarise yourself with the many layout options available. Now we add the capitals from previous episode in blue. tm_shape(africapitals) + tm_dots("blue", size=0.5)+ tm_shape(afrihighway) + tm_lines("red") It is great to see how the capitals are connected by the trans-African highway network. Note The order of tm_dots() and tm_lines() matters. If you want the points overlaying the lines, it should be placed after the lines coding and visa versa. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.2.1.1 Exercise 3 In the below exercise we have tried to visualise all the capitals and only the roads starting with the letter b. However, we have messed up the order of the code. Can you rearrange the code? # tm_shape(africapitals) + # tm_shape(afrihighway_ex1)+ # tm_dots("blue", size=0.5)+ # tm_lines("blue") #afrihighway_ex1=afrihighway[grep("^B", afrihighway$Name),] Answer: afrihighway_ex1=afrihighway[grep("^B", afrihighway$Name),] tm_shape(africapitals) + #important that capitals are visualised first tm_dots("blue", size=0.5)+ tm_shape(afrihighway_ex1)+ tm_lines("blue") div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.2.1.2 Exercise 4 Visualise the trans-African highway network, with line width associated with the length of the road. The function st_length is used to calculate the length of a line. Answer: #[julie-anne this seems to error] # Error: Assigned data `value` must be compatible with existing data. # x Existing data has 100 rows. # x Assigned data has 99 rows. # afrihighway$length=tapply(st_length(afrihighway), afrihighway$Name, sum) # tm_shape(afrihighway) + # tm_lines(lwd = `length`) 4.3 Polygons Polygons are lines with the same first and last coordinate. When the polygon line is connected, the same start and end point results in a closed shape. Similar to lines, depending on the detail of the map, more or less points can be used to create a polygon. This two-dimensional data is most often used to visualise country and continent boundaries. The continent outline of Africa is a multipolygon. plot(st_geometry(africontinent), col = "lightblue") One polygon is used to visualise the mainland of Africa. An additional polygon is used for Madagascar. Together they represent the whole African continent. Sometimes several polygons are necessary to capture a more complex shape. The different polygons in one data row indicate either areas to include or exclude from the final image. These are called multipolygons. An example of a multipolygon is the country border of South Africa. Lesotho is entirely surrounded by South Africa. If we want to visualise South Africa, we need to make sure that the Lesotho area is excluded. Visualisation of South Africa therefore requires two polygons, one to outline the outer borders and one to highlight the area to exclude (Lesotho country borders). Below, the South African border is visualised. africountries_ex=africountries %>% filter(`name` == "South Africa") plot(st_geometry(africountries_ex), col = "lightblue") As you can see in the image, when the polygon of South Africa is visualised, a white area is visible inside the country (representing Lesotho), which is not part of South Africa. 4.3.1 Example For this example, we will look at the country borders of African countries. Lets visualise the geometry of the datafile first. print(st_geometry(africountries)) #printing information on the geometry ## Geometry set for 51 features ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: -17.62504 ymin: -34.81917 xmax: 51.13387 ymax: 37.34999 ## Geodetic CRS: WGS 84 ## First 5 geometries: The country border file contains 51 country outlines with geometry type MULTIPOLYGON. If we print the first 6 rows of data, we can see how each country border is stored in the database. head(africountries) #First 6 rows of data are printed ## Simple feature collection with 6 features and 11 fields ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: -17.06342 ymin: -13.25723 xmax: 51.13387 ymax: 27.65643 ## Geodetic CRS: WGS 84 ## name name_long pop_est gdp_md_est lastcensus income_grp iso_a3 ## 1 Tanzania Tanzania 53950935 150600.0 2002 5. Low income TZA ## 2 W. Sahara Western Sahara 603253 906.5 NA 5. Low income ESH ## 11 Dem. Rep. Congo Democratic Republic of the Congo 83301151 66010.0 1984 5. Low income COD ## 12 Somalia Somalia 7531386 4719.0 1987 5. Low income SOM ## 13 Kenya Kenya 47615739 152700.0 2009 5. Low income KEN ## 14 Sudan Sudan 37345935 176300.0 2008 4. Lower middle income SDN ## geometry name_fr name_pt name_af ## 1 MULTIPOLYGON (((33.90371 -0... Tanzanie Tanzânia Tanzanië ## 2 MULTIPOLYGON (((-8.66559 27... Sahara occidental Saara Ocidental Wes-Sahara ## 11 MULTIPOLYGON (((29.34 -4.49... Congo-Kinshasa Congo - Kinshasa Demokratiese Republiek van die Kongo ## 12 MULTIPOLYGON (((41.58513 -1... Somalie Somália Somalië ## 13 MULTIPOLYGON (((39.20222 -4... Kenya Quênia Kenia ## 14 MULTIPOLYGON (((24.56737 8.... Soudan Sudão Soedan ## name_sw ## 1 Tanzania ## 2 Sahara Magharibi ## 11 Jamhuri ya Kidemokrasia ya Kongo ## 12 Somalia ## 13 Kenya ## 14 Sudan Here, the geometry data contain a list with (multiple) polygons, with each polygon represented as a list of data points with latitude and longitude. These points are connected to form polygons, which are either used to include or exclude areas from the final image. The geometry of the multipolygon data is stored as MULTIPOLYGON (((Latitude1, Longitude1, Latitude2, Longitude2, Latitude3, Longitude3,.. ),(Latitude1, Longitude1, ..)),(Latitude1, Longitude1, ))). Lets visualise these multipolygons with black lines. tm_shape(africountries) + tm_borders() #if only borders need to be visualised tm_shape(africountries) + tm_polygons() #if you want the image to specify the multipolygon area Now we can add the capitals and highways from previous episodes tm_shape(africountries) + tm_borders()+ tm_shape(africapitals) + tm_dots("blue", size=0.5)+ tm_shape(afrihighway) + tm_lines("red") div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.3.1.1 Exercise 5 Multiple choice to identify if datafiles contain point, line or (multi)polygon geometry. 1 Look up the bus routes in your home area. Which data type would you use to visualise this data? a Point data b Line data c Multipolygon data d All of the above answer: b 2 What kind of data type is necessary to visualise the countries part of the the Economic Community of West African States (ECWAS) community? a Point data b Line data c Multipolygon data d All of the above answer: c 3 Which data type is necessary for the authors to visualise the below image. (need help visualising this with the right approval from authors) https://www.google.com/url?sa=i&url=https%3A%2F%2Fcdiac.ess-dive.lbl.gov%2Fepubs%2Fndp%2Fndp055%2Fndp055.html&psig=AOvVaw2qJ0HAjtU9ytbSWT-qFR0R&ust=1616679119758000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKD8l5qFye8CFQAAAAAdAAAAABBW a Point data b Line data c Multipolygon data d All of the above answer: d div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.3.1.2 Exercise 6 Visualise the African borders of all countries with an area larger than 300.000 km^2. The function st_area is used to calculate the area within a polygon. Hint: make sure you check the units Answer: africountries$area_sqm <- st_area(africountries) africountries$area_sqkm <-africountries$area_sqm / 1000000 africountries_filtered = africountries %>% dplyr::filter(as.numeric(africountries$area_sqkm) > 300000) tm_shape(africountries_filtered) + tm_borders() 4.4 Rasters Points, lines and polygons, in their essence, consist of points with a longitude and latitude value. The data files of these vectors look very similar. Raster data are a group on their own. Raster data consist of a matrix of grid cells (pixels), with each grid cell representing a geographical location with a value illustrating a characteristic of that location. Raster data are mainly used when displaying data that are continuous accross space. For example, population density, landcover variation and elevation data extracted from satellites, drones and surveys. The more grid cells a raster file contains, the smoother the visualisation of the characteristic will be. However, a large number of grids also means a large heavy file, which may be difficult to run. Whenever you are working with raster files, think about your goal and objective. The highest resolution might not always be necessary. To read in raster data, we first need to install and load the raster package. #install.packages("raster") #install raster package library(raster) # load raster package We can now start visualising raster data. 4.4.1 Example For this example we use African population data from 2000 and 2020. Lets look at the information within the file first. print(afripop2000) #printing information on the raster data file ## class : RasterLayer ## dimensions : 434, 413, 179242 (nrow, ncol, ncell) ## resolution : 0.1666667, 0.1666667 (x, y) ## extent : -17.62625, 51.20708, -34.97542, 37.35792 (xmin, xmax, ymin, ymax) ## crs : +proj=longlat +datum=WGS84 +no_defs ## source : memory ## names : ppp_2000_1km_Aggregated ## values : 0, 16606.66 (min, max) The population raster data from 2000 contains 434 rows, 413 columns and a total of 179.242 grid cells with geometry type RasterLayer . Lets print the first 10 rows of data. head(afripop2000) #First 6 rows of data are printed ## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ## 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 5 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 6 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 7 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 8 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 9 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## 10 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Why do you think all rows are empty? Lets take a look at more grid cells. getValues(afripop2000) ## [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [11] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [21] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [31] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [41] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [51] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [61] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [71] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [81] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [91] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [101] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [111] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [121] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [131] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [141] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [151] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [161] NaN 31.530225 28.976320 27.053571 136.428734 294.236007 267.969128 NaN NaN NaN ## [171] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [181] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [191] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [201] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [211] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [221] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [231] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [241] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [251] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [261] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [271] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [281] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [291] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [301] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [311] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [321] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [331] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [341] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [351] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [361] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [371] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [381] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [391] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [401] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [411] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [421] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [431] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [441] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [451] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [461] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [471] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [481] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [491] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [501] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [511] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [521] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [531] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [541] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [551] NaN NaN NaN NaN NaN NaN 26.581936 57.259988 98.798142 NaN ## [561] NaN 10.485693 36.448088 56.846905 NaN NaN NaN NaN NaN NaN ## [571] NaN NaN 40.543849 46.735299 58.994084 38.973892 112.350208 219.639630 95.674532 84.673351 ## [581] NaN NaN NaN NaN 130.251743 NaN NaN NaN NaN NaN ## [591] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [601] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [611] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [621] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [631] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [641] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [651] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [661] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [671] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [681] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [691] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [701] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [711] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [721] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [731] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [741] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [751] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [761] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [771] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [781] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [791] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [801] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [811] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [821] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [831] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [841] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [851] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [861] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [871] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [881] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [891] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [901] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [911] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [921] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [931] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [941] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ## [951] NaN NaN NaN NaN NaN NaN 149.317101 78.438325 78.944654 20.285452 ## [961] 22.651681 2.156746 NaN NaN NaN NaN NaN NaN 53.467887 60.544859 ## [971] 100.295662 229.078813 38.838185 1500.185943 98.050085 44.672719 38.032209 57.407279 3322.625715 6.796631 ## [981] 17.307500 24.163841 147.894095 47.972929 109.734964 58.400623 78.840521 50.609101 52.652782 44.439908 ## [991] 52.390443 75.373201 523.321409 NaN NaN 22.653634 50.320826 76.936087 94.302234 NaN ## [ reached getOption("max.print") -- omitted 178242 entries ] The printed matrix shows that the raster layer consists of a matrix with values. The grid cells can be empty if no data is available. This just results in no visualisation (NA or empty) at those locations. Lets visualise the population data with the country borders. Note that population density data are highly skewed. To ensure both high and low density areas are clearly visible, we have to specify the data breaks manually. tm_shape(afripop2020) + tm_raster(breaks=c(0,2,20,200,2000,25000)) We can make the image easier to interpret by using a palette from the viridisLite package, moving the legend using tm_layout() and including the African borders. tm_shape(afripop2020) + tm_raster(palette = rev(viridisLite::magma(5)), breaks=c(0,2,20,200,2000,25000)) + #specify the breaks of the palette tm_layout(legend.position = c("left","bottom"))+ #moves the legend to the left bottom corner tm_shape(africountries) + tm_borders() Now we can add the capitals and highways from previous episodes. tm_shape(afripop2000) + tm_raster(palette = rev(viridisLite::magma(5)), breaks=c(0,2,20,200,2000,25000)) + tm_layout(legend.position = c("left","bottom"))+ tm_shape(africountries) + tm_borders() div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} 4.4.1.1 Exercise 7 Visualise the population data of 2000 using a different palette from the viridisLite package. Increase the number of breaks to six. Which breaks are most appropriate? tm_shape(afripop2020) + tm_raster(palette = rev(viridisLite::plasma(6)), breaks=c(0,2,20,200,2000,20000, 25000)) + tm_layout(legend.position = c("left","bottom"))+ tm_shape(africountries) + tm_borders() 4.5 Further resources If you are interested in learning more about the different spatial data types, please visit: Geospatial workshop Geospatial data organization Introduction to geospatial data Raster and vector data 4.6 Summary/key points The image below gives a short recap of the different data types discussed in this chapter. You should now be able to recognize, load and manipulate these data types using the sf and raster and visualise them using the tmap package. "],["visualising1.html", "Chapter 5 Visualising spatial data part 1: tmap and mapview 5.1 Overall goal of the chapter 5.2 Quick interactive maps with mapview 5.3 Static maps with tmap 5.4 Interactive maps with tmap 5.5 Further resources 5.6 Summary 5.7 Exercise solutions", " Chapter 5 Visualising spatial data part 1: tmap and mapview 5.1 Overall goal of the chapter In the previous section we explored different types of spatial data and looked at how these can be used to create a map. In this section we will use tmap and mapview packages to crate both static and interactive maps. In particular, we will focus on the goals presented below. div.green { background-color:#e3ffd9; border-radius: 5px; padding: 20px;} Learning objectives Create static and interactive maps using different packages Learn function structure to build more advanced maps Analyse the differences between used packages and identify their applicability for various purposes This chapter requires the following packages (some of them we used already): cran_packages_to_install <- c( "mapview", # map-making package for interactive maps "tmap", # map-making package for static and interactive maps "tidyverse", # metapackage containing dplyr, ggplot2 and other packages "sf", # package for working with spatial data "rnaturalearth", # data package "rnaturalearthdata", # data package "tmaptools" # map building package ) install.packages(cran_packages_to_install) remotes::install_github("afrimapr/afrilearnr") #remotes::install_github("r-spatial/mapview@develop") #remotes::install_github("afrimapr/afrilearndata") Next, we need to load the packages: library(tmap) library(mapview) library(ggplot2) library(sf) library(afrilearndata) library(rnaturalearth) library(rnaturalearthdata) library(dplyr) library(tmaptools) #library(afrilearnr) 5.2 Quick interactive maps with mapview Mapview package allows quickly and easily create interactive maps of spatial data. Therefore, it is useful when we want to quickly explore the data visually without excessive care about the quality of the presentation. However, if we need static maps or interactive maps which are more elaborate we might want to consider other options such as tmap package which will be presented later in this chapter. The typical spatial objects types supported by mapview package are: sf raster sp To create the most basic map with the boundaries of African countries we call mapview() function # data(africountries) # mapview(africountries) This map has a number of functions: layer button to switch between five different layers scale bar zoom butttons data name in the top right corner We can easily fill an interactive map with the colours based on one of the columns. Here we use population column to colours our map. Importantly, when we hoover over specific country the population data for a given country is showed. #mapview(africountries, zcol = ("pop_est")) Similarly, we can control for other features such as line width (lwd), colour of polygons (col.regions). Another important feature that we might want to control is the underlying map which we set with map.types argument. The available background maps can be viewed here. #mapview(africountries, color = "red", # lwd = 1.5, col.regions = "white", map.types = "Esri.WorldShadedRelief") Further, mapview allows us to easily build up many layers within a single map. Here, we firstly include countries and then add location of airports. Further a useful option is layer.name which allows us to control the naming of different layers of the map. The specific layers can be controlled and adjusted as showed in the example. In partucular, we set the colour of countries polygons according to the population size. It is possible to use layer button to hide and unhide layers of the map. # # simple map with two layers # # data(afriairports) # mapview(list(africountries,afriairports), layer.name = c("Countries", "Airports")) # # #map with advanced layers options # mapview(africountries, zcol = "pop_est", layer.name = "Population") + # mapview(afriairports, layer.name = "Airports location") The link to full documentation is available in Further resources section. 5.2.1 Exercises div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.2.1: Create a map with two layers: countries and capitals. Fill the country polygons according to income group. Explore the layers button to hide and unhide some of them. 5.3 Static maps with tmap In this section we explore the potential of tmap in creating static maps, which is a flexible, yet user-friendly package. Its syntax is similar to ggplot2 (plot-making package), where additional features of the map are simply build up on top of the basic structure. Before we plot the first maps we need to create a dataset called africa and activate static map viewing mode. africa <- ne_countries(continent = 'africa', scale = "medium", returnclass = "sf") tmap_mode("plot") #activates static map viewing mode Next, we create an empty contour map of the continent, where tm_shape() function serves as a basic component containing the shape object i.e. our spatial dataset. On top of this basic element we can then add more layers using + operator. The advantage of tmap package is that it offers a large variety layers and these are named relatively intuitively to make the search and use easier. For example, we will now use layer called tm_borders() which defines the borders of the polygons. Further, we create an empty, borderless map using tm_fill() which defines the fill of the polygons. tm_shape(africa)+ tm_borders() tm_shape(africa)+ tm_fill() Intuitively to create a map with both layers, we need to include tm_fill() and tm_borders() simultaneously. Alternatively, tm_polygons() function allows us to achieve exactly the same result more efficiently. It draws the polygons borders and fills them. tm_shape(africa)+ tm_borders()+ tm_fill() tm_shape(africa)+ tm_polygons() We can further develop our map by adjusting different features of the map such as colour and transparency of the map, width and types of the border lines etc. The extra parameters for changing the plot elements can be found here. tm_shape(africa)+ tm_polygons(col = "green", lty = "dotted", alpha = 0.3) As we already know a basic structure required to build a static map, we can proceed to a more advanced (and useful) example, where we fill the polygons using data on last census and adding relevant title to the legend. Further, we can build on the previous map by adding labels for country names with tm_text function. In a similar manner a variety of different layers can be added. tm_shape(africa)+ tm_polygons(col = "lastcensus", title = "Year of last census") tm_shape(africa)+ tm_polygons(col = "lastcensus", title = "Year of last census")+ tm_text("admin", size = 0.52, fontface = "bold", auto.placement = TRUE) Figure 5.1: Basic map without labesl (left) and map with added coutries names (right) Another useful function in tmap is the adjustment of the intervals in the legend, in case the default scale does not provide enough variety. For example, plotting the population of African countries on the map using default intervals (stemming from the data) is not very informative due to to much clustering of information. Instead, we might want to use breaks argument to set them up manually to provide more differentiation visually. For clarity, I set up the customised breaks outside of the map-making function. Alternatively, we can control number of so-called bins (groups) into which the Population is divided, by setting n argument to a desired number of bins inside the tm_polygons function. #default settings tm_shape(africa)+ tm_polygons(col = "pop_est", title = "Population") #set up breaks manually custom_breaks = c(0, 1, 4, 7, 10, 30, 50, 70, 100, 120, 150) * 1000000 tm_shape(africa)+ tm_polygons(col = "pop_est", title = "Population", breaks = custom_breaks) #set up a number of bins tm_shape(africa)+ tm_polygons(col = "pop_est", title = "Population", n = 15) Figure 5.2: Africas population with default breaks (left), customised breaks (middle) and divided in bins (right). So far, we used continuous variables to fill the polygons but it is also possible to use categorical variables for this purpose. In the example below income_grp variable is a categorical variable with income level. It allows for visual grouping of countries in the same category. The names of the categories in the legend were adjusted using labels argument. In the similar manner we can show the airports of Africa according to their size. tm_shape(africa)+ tm_polygons(col = "income_grp", title = "Income levels", alpha = 0.6, labels = c("High", "Upper middle", "Lower middle", "Lower")) data(afriairports) tm_shape(africontinent)+ tm_polygons(col = "lightyellow")+ tm_shape(afriairports)+ tm_dots(col = "type", shape = 21, size = 0.2, title = "Airport size", labels = c("Large", "Medium", "Small"), palette=c(large_airport='red', medium_airport='yellow', small_airport='blue')) It is important to bear in mind that same information can be displayed on the map in many different ways. For example, we can make use of tm_bubbles to create so called bubbles which size is linked to the population of each country while their colour related to the income group. tm_shape(africa)+ tm_polygons(col = "lightyellow")+ tm_bubbles(size = "pop_est", col = "income_grp", title.col = "Income level", title.size = "Population") 5.3.1 Colour setting and colour pallete An important aspect of the maps, as in every visual representation, are the colours. In tmap we can change the default colours using palette argument. In the example below, we used palette called Set1 and plasma and there are many other options to choose from. To view them, we run tmaptools::palette_explorer() which will open a new window with a wide range of palettes. Sliders on the left hand side allow selecting a number of colours. tm_shape(africa)+ tm_polygons(col = "lastcensus", title = "Year of last census", palette = "Set1") tm_shape(africa)+ tm_polygons(col = "lastcensus", title = "Year of last census", palette = "plasma") Figure 5.3: Africas maps using different pallete options. Alternatively an overall style of a single map can be easily changed using tm_style function. However, it might also be useful to change the style in all the maps in the document. This can be achieved with setting the style globally with tmap_style(\"nameofthestyle\"). The default style is called white, hence to restore a default style setting use tmap_style(\"white\"). tm_style("classic")+ tm_shape(africa)+ tm_polygons()+ tm_bubbles(size = "pop_est", col = "income_grp", title.col = "Income level", title.size = "Population", labels = c("High", "Upper middle", "Lower middle", "Lower")) tm_style("beaver")+ tm_shape(africa)+ tm_polygons()+ tm_bubbles(size = "pop_est", col = "income_grp", title.col = "Income level", title.size = "Population", labels = c("High", "Upper middle", "Lower middle", "Lower")) tm_style("albatross")+ tm_shape(africa)+ tm_polygons()+ tm_bubbles(size = "pop_est", col = "income_grp", title.col = "Income level", title.size = "Population", labels = c("High", "Upper middle", "Lower middle", "Lower")) Figure 5.4: Examples of different styles. 5.3.2 Visualising different datasets in one map tmap not only allows us to add extra layers to a single map by building on a basic structure, but it also enables us to join two separate datasets in a single map. We first create an object called countries which is a map with African countries: #read in data data(africountries) #create an object countries = tm_shape(africountries)+ tm_polygons(col = "lightblue", alpha = 0.3) #view object called "countries" countries Then we use it as an argument to merge it with a map containing the location of capitals. #read in data with capitals data(africapitals) #merge two maps countries+ tm_shape(africapitals)+ #uses dataset with capitals tm_dots(col = "red", size = 0.15)+ #adds dots on the map tm_layout(title = "Capital cities of Africa" , title.position = c("right", "top"), title.size = 1) #add and adjust map title 5.3.3 Exercises The solution to the exercises are provided at the end of the chapter. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.3.1: Plot a yellow map of Africa with transparency of 0.4 and solid line borders of width 3. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.3.2: Plot a lightblue map of Africa with dotted, non-transparent, red borders. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.3.3: Plot a map that has polygons filled with gross domestic product, black borders, legend titled GDP and customised breaks at 0, 20000, 30000, 40000, 50000, 100000, 200000, 300000, 500000. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.3.4: Create a map with continent contour in light green colour. Then add african highways by using afrihighway dataset. Finally, include a title on the bottom of the map. 5.4 Interactive maps with tmap tmappackage offers versatility not only for creating static maps, as we have seen above, but it also allows for making customised interactive maps conveniently by simply changing the mode of operation from static to dynamic using plot or view, respectively in tmap_mode() function. After the activation of an interactive mode all the maps produced with tmap will be interactive. Therefore, we are able to create all the maps that we have produced so far in an interactive version. #sets interactive mode tmap_mode("view") ## tmap mode set to interactive viewing tm_shape(africa)+ tm_borders()+ tm_shape(africapitals)+ tm_dots(col = "white", border.col = "blue", size = 0.1)+ #capital dots settings tm_text("capitalname")+ #adds capital names tm_shape(afrihighway)+ tm_lines(col = "red", lwd = 2, alpha = 0.7) #highway lines setting Regardless of the mode, the creation of maps using tmap package is easy and convenient. The additional feature in the interactive mode is the choice of the background map. This can be set up using function tm_basemap. Available base maps can be accessed using leaflet::providers. They can also be previewed here. In the example below, we use a topographic map of Africa. tm_basemap("OpenTopoMap")+ tm_shape(africa)+ tm_borders()+ tm_shape(africapitals)+ tm_dots(col = "black")+ #capital dots settings tm_shape(afrihighway)+ tm_lines(col = "red", lwd = 2, alpha = 0.7) #highway lines setting 5.4.1 Visualising subsets of data Lets assume that we are only interested in the subset of our data for example a specific country or the location of large airports only. We can achieve it using dplyr package. tmap_mode("view") ## tmap mode set to interactive viewing data(afriairports) #take a subset of data large = afriairports %>% filter(type=="large_airport") #plot the subset tm_shape(africa)+ tm_borders()+ tm_shape(large)+ tm_dots( col = "red") 5.4.2 Exercises div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.4.1: Create an interactive map uses watercolour theme, the highways are blue and dots denoting capitals are white with black borders. Finally, add capitalnames. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 5.4.2: Create an interactive map of African countries which have population smaller than 10 million. Fill the polygons with the population size. 5.5 Further resources tmap documentation Mapview documentation 5.6 Summary In this chapter we looked at how to produce static and interactive maps using different packages. Specifically, we saw that the tmap package is a flexible tool to create maps with a stepwise approach, where we can add different layers to our maps. It is equally easy to switch between static and interactive maps. Further, mapview was showed to be a quick solution for creating interactive maps. 5.7 Exercise solutions Exercise 5.2.1 #mapview(africountries, zcol = "income_grp") + mapview(africapitals) Exercise 5.3.1 tm_shape(africa)+ tm_polygons(col = "yellow", lwd = 3, lty = "solid", alpha = 0.4) Exercise 5.3.2 tm_shape(africa)+ tm_fill(col = "lightblue")+ tm_borders(col = "red", lty = "dotted", alpha = 1) Exercise 5.3.3 custom_breaks = c(0, 2, 3, 4, 5, 10,20, 30, 50) * 10000 tm_shape(africa)+ tm_polygons(col = "gdp_md_est", title = "GDP", breaks = custom_breaks) Exercise 5.3.4 map_contour = tm_shape(africa)+ tm_fill(col = "lightgreen") data(afrihighway) map_contour + tm_shape(afrihighway)+ tm_lines()+ tm_layout(title = "Highways in Africa", title.position = c("center", "bottom")) Exercise 5.4.1 tmap_mode("view") ## tmap mode set to interactive viewing tm_basemap("Stamen.Watercolor")+ tm_shape(africa)+ tm_borders()+ tm_shape(africapitals)+ tm_dots(col = "white", border.col = "black")+ #capital dots settings tm_text("capitalname", size = 1.2)+ tm_shape(afrihighway)+ tm_lines(col = "blue", lwd = 3) #highway lines setting Exercise 5.4.2 tmap_mode("view") ## tmap mode set to interactive viewing data(africountries) #take a subset of data small = africountries %>% filter(pop_est < 10000000) tm_shape(small)+ tm_polygons(col = "pop_est") "],["shiny.html", "Chapter 6 Shiny interactive map applications", " Chapter 6 Shiny interactive map applications Use of the shiny package to make interactive applications displaying maps. We start with a very simple example showing how you can create a small application that allows a user to choose from a list of countries and then displays the outline of that country on a map. [andy (or anyone else) to look at best ways of demoing shinyapps in a book] # save this code in a single file called app.r # then the shiny app can be run from RStudio using the 'Run' button # (above the text editor window) # or can just copy & paste code into the console library(afrilearndata) library(dplyr) library(mapview) library(leaflet) # User Interface ui <- bootstrapPage( # allow user to choose a country selectInput('country_choice', label='choose a country', choices = sort(africountries$name)), # plot map leafletOutput("serve_map") ) # server code (does things requested by the UI) server <- function(input, output) { output$serve_map <- renderLeaflet({ # filter selected_country <- dplyr::filter(africountries, name==input$country_choice) mapplot <- mapview(selected_country, zcol="name") mapplot@map }) } # Return a Shiny app object shinyApp(ui = ui, server = server) "],["data-sources.html", "Chapter 7 Sources of data 7.1 Administrative boundaries 7.2 Population 7.3 Open Street Map data 7.4 Elevation 7.5 Temperature 7.6 Rainfall 7.7 Vegetation and Land cover 7.8 Demographic and Health Survey (DHS) 7.9 Malaria", " Chapter 7 Sources of data Here we show several R packages that can be used to download spatial data including administrative boundaries, population, climatic, and health data. We give short reproducible examples on how to download and visualize spatial data that can be useful in different settings. More extended examples and details about the capabilities of each of the packages can be seen at https://rspatialdata.github.io/ and the packages websites. 7.1 Administrative boundaries We can download administrative boundaries of countries with the rgeoboundaries package. For example, we can download the administrative boundaries of Nigeria with geoboundaries() as follows. library(rgeoboundaries) library(ggplot2) map <- geoboundaries("Nigeria") ggplot(data = map) + geom_sf() We can also download administrative boundaries of multiple countries and different administrative levels. map <- geoboundaries(c("Nigeria", "Chad"), "adm1") ggplot(data = map) + geom_sf() 7.2 Population The wopr package provides access to the WorldPop Open Population Repository and provides estimates of population sizes for specific geographic areas. To download the population data we first use getCatalogue() to retrieve the WOPR data catalogue and see a list of currently available databases. #install.packages("remotes") library(remotes) ## Warning: package 'remotes' was built under R version 4.0.5 remotes::install_github('wpgp/wopr') ## Skipping install of 'wopr' from a github remote, the SHA1 (6a4abcf0) has not changed since last install. ## Use `force = TRUE` to force installation library(wopr) catalogue <- getCatalogue(spatial_query = T) ## Registered S3 method overwritten by 'httr': ## method from ## print.cache_info hoardr catalogue ## country version ## 25 BFA v1.0 ## 64 COD v1.0 ## 70 COD v2.0 ## 134 GHA v2.0 ## 197 MOZ v1.1 ## 241 NGA v1.2 ## 281 SSD v2.0 ## 338 ZMB v1.0 Then, we subset the catalogue for the country (e.g. Nigeria with ISO code NGA) and download the data for the selection using the downloadData() function. selection <- subset(catalogue, country == "NGA" & category == "Population" & version == "v1.2") downloadData(selection) Finally, we use the sf package to read in the downloaded shapefile and plot it with ggplot(). [Paula: Ive set this to eval=FALSE for now to avoid filenotfound error, can we make this runnable ?, Andy] library(sf) library(ggplot2) map <- st_read("data/NGA_population_v1_2_admin_level2_boundaries.shp") ## Reading layer `NGA_population_v1_2_admin_level2_boundaries' from data source `C:\\Users\\User\\OneDrive - University of Leeds\\Documents\\afrimapr-book\\data\\NGA_population_v1_2_admin_level2_boundaries.shp' using driver `ESRI Shapefile' ## Simple feature collection with 37 features and 17 fields ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: 2.6925 ymin: 4.271484 xmax: 14.67797 ymax: 13.88571 ## Geodetic CRS: WGS 84 ggplot(map, aes(fill = mean)) + geom_sf() + scale_fill_continuous(name = "Population") 7.3 Open Street Map data We can retrieve Open Street Map data using the osmdata package. The available_features() function can be used to get the list of recognized features in OSM. The available_tags() function lists out the tags associated with each feature. A list of the available features can be found in the OSM wiki. library(osmdata) ## Warning: package 'osmdata' was built under R version 4.0.5 ## Data (c) OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright head(available_features()) ## [1] "4wd_only" "abandoned" "abutters" "access" "addr" "addr:city" head(available_tags("amenity")) ## [1] "animal_boarding" "animal_breeding" "animal_shelter" "arts_centre" "atm" "baby_hatch" The first step in creating an osmdata query is defining the geographical area we wish to include in the query. This can be done by defining a bounding box that defines a geographical area by its bounding latitudes and longitudes. lagos_bb <- getbb("Lagos") lagos_bb ## min max ## x 3.234180 3.554180 ## y 6.295058 6.615057 To retrieve the required features of a place (defined by the bounding box), we have to then create an overpass query with opq(). Then, the add_osm_feature() function can be used to add the required features to the query. Finally, we use the osmdata_sf() function to obtain a simple feature object of the resultant query. lagos_hospitals <- lagos_bb %>% opq() %>% add_osm_feature(key = "amenity", value = "hospital") %>% osmdata_sf() We can visualise an interactive map of the hospitals in Lagos as follows. library(leaflet) leaflet() %>% addTiles() %>% addPolygons(data = lagos_hospitals$osm_polygons, label = lagos_hospitals$osm_polygons$name) 7.4 Elevation The elevatr package can be used to download elevation data. We can use get_elev_raster() to obtain the elevation of Ghana as follows. install.packages("elevatr") ## Installing package into 'C:/Users/User/OneDrive - University of Leeds/Documents/R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'elevatr' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ## C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa\\downloaded_packages library(ggplot2) library(raster) library(elevatr) ## Warning: package 'elevatr' was built under R version 4.0.5 library(rgeoboundaries) library(sf) library(viridis) ## Loading required package: viridisLite map <- geoboundaries("Ghana") elevation_data <- get_elev_raster(locations = map, z = 9, clip = "locations") ## Warning in st_buffer.sfc(st_geometry(x), dist, nQuadSegs, endCapStyle = endCapStyle, : st_buffer does not correctly buffer longitude/ ## latitude data ## dist is assumed to be in decimal degrees (arc_degrees). ## Downloading DEMs [>--------------------------] 2% eta: 41s Downloading DEMs [>--------------------------] 3% eta: 37s Downloading DEMs [>--------------------------] 4% eta: 33s Downloading DEMs [>--------------------------] 5% eta: 30s Downloading DEMs [=>-------------------------] 6% eta: 27s Downloading DEMs [=>-------------------------] 7% eta: 26s Downloading DEMs [=>-------------------------] 8% eta: 24s Downloading DEMs [==>------------------------] 9% eta: 23s Downloading DEMs [==>------------------------] 10% eta: 22s Downloading DEMs [==>------------------------] 11% eta: 22s Downloading DEMs [==>------------------------] 12% eta: 21s Downloading DEMs [===>-----------------------] 14% eta: 20s Downloading DEMs [===>-----------------------] 15% eta: 20s Downloading DEMs [===>-----------------------] 16% eta: 19s Downloading DEMs [===>-----------------------] 17% eta: 19s Downloading DEMs [====>----------------------] 18% eta: 18s Downloading DEMs [====>----------------------] 19% eta: 19s Downloading DEMs [====>----------------------] 20% eta: 18s Downloading DEMs [=====>---------------------] 21% eta: 18s Downloading DEMs [=====>---------------------] 22% eta: 18s Downloading DEMs [=====>---------------------] 23% eta: 18s Downloading DEMs [=====>---------------------] 24% eta: 18s Downloading DEMs [======>--------------------] 25% eta: 17s Downloading DEMs [======>--------------------] 26% eta: 17s Downloading DEMs [======>--------------------] 27% eta: 17s Downloading DEMs [=======>-------------------] 28% eta: 16s Downloading DEMs [=======>-------------------] 29% eta: 16s Downloading DEMs [=======>-------------------] 30% eta: 16s Downloading DEMs [=======>-------------------] 31% eta: 16s Downloading DEMs [========>------------------] 32% eta: 16s Downloading DEMs [========>------------------] 33% eta: 15s Downloading DEMs [========>------------------] 34% eta: 15s Downloading DEMs [=========>-----------------] 35% eta: 15s Downloading DEMs [=========>-----------------] 36% eta: 15s Downloading DEMs [=========>-----------------] 38% eta: 15s Downloading DEMs [=========>-----------------] 39% eta: 14s Downloading DEMs [==========>----------------] 40% eta: 14s Downloading DEMs [==========>----------------] 41% eta: 14s Downloading DEMs [==========>----------------] 42% eta: 14s Downloading DEMs [===========>---------------] 43% eta: 14s Downloading DEMs [===========>---------------] 44% eta: 13s Downloading DEMs [===========>---------------] 45% eta: 13s Downloading DEMs [===========>---------------] 46% eta: 13s Downloading DEMs [============>--------------] 47% eta: 12s Downloading DEMs [============>--------------] 48% eta: 12s Downloading DEMs [============>--------------] 49% eta: 12s Downloading DEMs [=============>-------------] 50% eta: 12s Downloading DEMs [=============>-------------] 51% eta: 11s Downloading DEMs [=============>-------------] 52% eta: 11s Downloading DEMs [=============>-------------] 53% eta: 11s Downloading DEMs [==============>------------] 54% eta: 11s Downloading DEMs [==============>------------] 55% eta: 10s Downloading DEMs [==============>------------] 56% eta: 10s Downloading DEMs [==============>------------] 57% eta: 10s Downloading DEMs [===============>-----------] 58% eta: 10s Downloading DEMs [===============>-----------] 59% eta: 9s Downloading DEMs [===============>-----------] 60% eta: 9s Downloading DEMs [================>----------] 61% eta: 9s Downloading DEMs [================>----------] 62% eta: 9s Downloading DEMs [================>----------] 64% eta: 9s Downloading DEMs [================>----------] 65% eta: 8s Downloading DEMs [=================>---------] 66% eta: 8s Downloading DEMs [=================>---------] 67% eta: 8s Downloading DEMs [=================>---------] 68% eta: 8s Downloading DEMs [==================>--------] 69% eta: 7s Downloading DEMs [==================>--------] 70% eta: 7s Downloading DEMs [==================>--------] 71% eta: 7s Downloading DEMs [==================>--------] 72% eta: 7s Downloading DEMs [===================>-------] 73% eta: 6s Downloading DEMs [===================>-------] 74% eta: 6s Downloading DEMs [===================>-------] 75% eta: 6s Downloading DEMs [====================>------] 76% eta: 6s Downloading DEMs [====================>------] 77% eta: 6s Downloading DEMs [====================>------] 78% eta: 6s Downloading DEMs [====================>------] 79% eta: 5s Downloading DEMs [=====================>-----] 80% eta: 5s Downloading DEMs [=====================>-----] 81% eta: 5s Downloading DEMs [=====================>-----] 82% eta: 5s Downloading DEMs [=====================>-----] 83% eta: 4s Downloading DEMs [======================>----] 84% eta: 4s Downloading DEMs [======================>----] 85% eta: 4s Downloading DEMs [======================>----] 86% eta: 4s Downloading DEMs [=======================>---] 88% eta: 3s Downloading DEMs [=======================>---] 89% eta: 3s Downloading DEMs [=======================>---] 90% eta: 3s Downloading DEMs [=======================>---] 91% eta: 3s Downloading DEMs [========================>--] 92% eta: 2s Downloading DEMs [========================>--] 93% eta: 2s Downloading DEMs [========================>--] 94% eta: 2s Downloading DEMs [=========================>-] 95% eta: 1s Downloading DEMs [=========================>-] 96% eta: 1s Downloading DEMs [=========================>-] 97% eta: 1s Downloading DEMs [=========================>-] 98% eta: 1s Downloading DEMs [==========================>] 99% eta: 0s Downloading DEMs [===========================] 100% eta: 0s ## Mosaicing & Projecting ## Clipping DEM to locations ## Note: Elevation units are in meters. ## Note: The coordinate reference system is: ## GEOGCRS["WGS 84 (with axis order normalized for visualization)", ## DATUM["World Geodetic System 1984", ## ELLIPSOID["WGS 84",6378137,298.257223563, ## LENGTHUNIT["metre",1]]], ## PRIMEM["Greenwich",0, ## ANGLEUNIT["degree",0.0174532925199433]], ## CS[ellipsoidal,2], ## AXIS["geodetic longitude (Lon)",east, ## ORDER[1], ## ANGLEUNIT["degree",0.0174532925199433, ## ID["EPSG",9122]]], ## AXIS["geodetic latitude (Lat)",north, ## ORDER[2], ## ANGLEUNIT["degree",0.0174532925199433, ## ID["EPSG",9122]]]] elevation_data <- as.data.frame(elevation_data, xy = TRUE) colnames(elevation_data)[3] = "elevation" #remove rows of data frame with one or more NA's using complete.cases elevation_data <- elevation_data[complete.cases(elevation_data), ] ggplot() + geom_raster(data = elevation_data, aes(x = x, y = y, fill = elevation)) + geom_sf(data = map, color = "white", fill = NA) + coord_sf() + scale_fill_viridis_c() + ggtitle("Elevation") 7.5 Temperature The raster package provides access to the WorldClim database, and allows us to download data sets on the many different climatic conditions. For example, we can can download maximum temperature at a resolution of 10 minutes as follows. library(raster) library(ggplot2) tmax_data <- getData(name = "worldclim", var = "tmax", res = 10) # Degrees Celsius gain(tmax_data) <- 0.1 # Converting the raster object into a dataframe tmax_data_may_df <- as.data.frame(tmax_data$tmax5, xy = TRUE, na.rm = TRUE) rownames(tmax_data_may_df) <- c() # Plot ggplot(data = tmax_data_may_df, aes(x=x,y=y)) + geom_raster(aes(fill = tmax5)) + labs(title = "Maximum temperature in May", subtitle = "For the years 1970-2000") + xlab("Longitude") + ylab("Latitude") + scale_fill_gradientn(name = "Temperature (°C)", colours=c("#0094D1","#68C1E6", "#FEED99","#AF3301"), breaks = c(-20, 0, 20, 40)) ## Warning: Raster pixels are placed at uneven vertical intervals and will be shifted. Consider using geom_tile() instead. 7.6 Rainfall The nasapower package aims at making it quick and easy to automate downloading NASA POWER (NASA Prediction of Worldwide Energy Resource) global meteorology, surface solar energy and climatology data. For example, we can use get_power(), to obtain global rainfall (specifying pars = \"PRECTOT\") or humidity (specifying pars = \"RH2M\"). library(nasapower) library(terra) library(viridis) climate_avg <- get_power(community = "AG", pars = "PRECTOT", lonlat = "GLOBAL", temporal_average = "CLIMATOLOGY") library("rnaturalearth") map <- ne_countries(returnclass = "sf") climate_box <- split(climate_avg, climate_avg$PARAMETER) climate_box <- lapply(climate_box, function(x){ x["PARAMETER"] <- NULL x}) climate_box <- lapply(X = climate_box, FUN = as.matrix) #retrieving precipitation data using the above made climate_box() function PRECTOT <- terra::rast(climate_box$PRECTOT[,c(1:2, 15)], crs = "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", type = "xyz") #converting above raster object into a data.frame for mapping PRECTOT_df <- as.data.frame(PRECTOT, xy = TRUE, na.rm = TRUE) rownames(PRECTOT_df) <- c() #plotting the graph ggplot() + geom_raster(data = PRECTOT_df, aes(x = x, y = y, fill = ANN)) + geom_sf(data = map, inherit.aes = FALSE, fill = NA) + scale_fill_viridis() + labs(title = "Rainfall in inches", fill = "Annual Rainfall") 7.7 Vegetation and Land cover MODIStsp is an R package for downloading and preprocessing time series of raster data from MODIS data products. Here, we use the Vegetation Indices 16-Day L3 Global 250 product with the product IDs MOD13Q1(Terra Product ID), and MYD13Q1(Aqua Product ID), but will be represented by M*D13Q1 - the second character is replaced by an asterix(*) to identify both Terra and Aqua. We can also download the Land Cover Type Yearly L3 Global 500m product with the product ID MCD12Q1 (Combined Aqua and Terra Product ID) install.packages("MODIStsp") ## Installing package into 'C:/Users/User/OneDrive - University of Leeds/Documents/R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'MODIStsp' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ## C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa\\downloaded_packages library(MODIStsp) ## Warning: package 'MODIStsp' was built under R version 4.0.5 library(rgeoboundaries) library(sf) # Downloading the country boundary map_boundary <- geoboundaries("Kenya") # Defining filepath to save downloaded spatial file spatial_filepath <- "map.shp" # Saving downloaded spatial file on to our computer #st_write(map_boundary, paste0(spatial_filepath)) MODIStsp(gui = FALSE, out_folder = "VegetationData", out_folder_mod = "VegetationData", selprod = "Vegetation_Indexes_16Days_1Km (M*D13A2)", bandsel = "NDVI", user = "mstp_test" , password = "MSTP_test_01", start_date = "2020.06.01", end_date = "2020.06.01", verbose = FALSE, spatmeth = "file", spafile = spatial_filepath, out_format = "GTiff") [Paula: Ive set this to eval=FALSE for now to avoid filenotfound error, can we make this runnable ?, Andy] # Reading in the downloaded NDVI raster data NDVI_raster <- raster("VegetationData/map/VI_16Days_1Km_v6/NDVI/MYD13A2_NDVI_2020_153.tif") # Transforming the data NDVI_raster <- projectRaster(NDVI_raster, crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") # Cropping the data NDVI_raster <- raster::mask(NDVI_raster, as_Spatial(map_boundary)) # Dividing values by 10000 to have NDVI values between -1 and 1 gain(NDVI_raster) <- 0.0001 # Converting the raster object into a dataframe NDVI_df <- as.data.frame(NDVI_raster, xy = TRUE, na.rm = TRUE) rownames(NDVI_df) <- c() # Visualising using ggplot2 ggplot() + geom_raster(data = NDVI_df, aes(x = x, y = y, fill = MYD13A2_NDVI_2020_153)) + geom_sf(data = map_boundary, inherit.aes = FALSE, fill = NA) + scale_fill_viridis(name = "NDVI") + labs(title = "NDVI (Normalized Difference Vegetation Index)", subtitle = "01-06-2020", x = "Longitude", y = "Latitude") 7.8 Demographic and Health Survey (DHS) The rdhs packages gives the users the ability to access and make analysis on the Demographic and Health Survey (DHS) data. For example we can find out the trends in antimalarial use in Africa as follows. install.packages("rdhs") ## Installing package into 'C:/Users/User/OneDrive - University of Leeds/Documents/R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'rdhs' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ## C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa\\downloaded_packages library(rdhs) ## Warning: package 'rdhs' was built under R version 4.0.5 # Make an api request resp <- dhs_data(indicatorIds = "ML_FEVT_C_AML", surveyYearStart = 2010, breakdown = "subnational") ## Writing your configuration to: ## -> C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa/rdhs/rdhs.json ## You have not granted permision to rdhs to write outside of ## your temporary directory. As a result any datasets or API ## calls will not be saved after you close this R sessiton. ## To cache your results please use set_rdhs_config() # filter it to 12 countries for space countries <- c("Angola","Ghana","Kenya","Liberia", "Madagascar","Mali","Malawi","Nigeria", "Rwanda","Sierra Leone","Senegal","Tanzania") library(ggplot2) ggplot(resp[resp$CountryName %in% countries, ], aes(x = SurveyYear, y = Value, colour = CountryName)) + geom_point() + geom_smooth(method = "glm") + theme(axis.text.x = element_text(angle = 90, vjust = .5)) + ylab(resp$Indicator[1]) + facet_wrap(~ CountryName, ncol = 6) ## `geom_smooth()` using formula 'y ~ x' 7.9 Malaria The malariaAtlas package can be used to download, visualise and manipulate global malaria data hosted by the Malaria Atlas Project. The package enables users to download the following types of data: parasite rate (PR) survey data (Plasmodium falciparum and Plasmodium vivax) vector occurrence data administrative boundary shapefiles to visualise data rasters covering a range of modelled outputs related to malaria research such as predicted malaria parasite prevalence For example, we can download parasite rate survey data corresponding to Zimbabwe as follows. install.packages("malariaAtlas") ## Installing package into 'C:/Users/User/OneDrive - University of Leeds/Documents/R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'malariaAtlas' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ## C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa\\downloaded_packages library(malariaAtlas) ## Warning: package 'malariaAtlas' was built under R version 4.0.5 d <- getPR(country = "Zimbabwe", species = "BOTH") ## Creating list of countries for which MAP data is available, please wait... ## Confirming availability of PR data for: Zimbabwe... ## PR points are available for Zimbabwe. ## Attempting to download PR point data for Zimbabwe ... ## Data downloaded for Zimbabwe. ## NOTE: All available data for this query was downloaded for both species, ## but there are no PR points for P. vivax in this region in the MAP database. ## To check endemicity patterns or to contribute data, visit malariaatlas.org OR email us at [email protected]. autoplot(d) ## OGR data source with driver: ESRI Shapefile ## Source: "C:\\Users\\User\\AppData\\Local\\Temp\\RtmpYTcVDa\\shp\\shp24b81a0e7c91\\mapadmin_0_2018.shp", layer: "mapadmin_0_2018" ## with 1 features ## It has 8 fields ## Regions defined for each Polygons "],["joining.html", "Chapter 8 Join non-spatial data onto spatial", " Chapter 8 Join non-spatial data onto spatial This chapter demonstrated how to join non-spatial data from different sources into spatial "],["raster.html", "Chapter 9 Raster manipulation", " Chapter 9 Raster manipulation e.g. summarising data by areas "],["openstreetmap.html", "Chapter 10 OpenStreetMap data", " Chapter 10 OpenStreetMap data what they are and how to use them? "],["data-editing.html", "Chapter 11 Creating and editing spatial data 11.1 Create a vector file from scratch", " Chapter 11 Creating and editing spatial data How to create and edit spatial data with examples 11.1 Create a vector file from scratch "],["visualising2.html", "Chapter 12 Visualising spatial data part 2", " Chapter 12 Visualising spatial data part 2 More advanced techniques of visualising of spatial data "],["case-study1.html", "Chapter 13 Case study 1 13.1 Health facility locations (probably)", " Chapter 13 Case study 1 13.1 Health facility locations (probably) "],["case-study2.html", "Chapter 14 Case study 2", " Chapter 14 Case study 2 To be decided "],["references.html", "References", " References Hijmans, R., J.(2020) Spatial Data Science. https://rspatial.org/intr/ Wickham, H. & Jenny Bryan. (2021). R packages: organize, test, document, and share your code. OReilly Media, Inc. 2nd edition. https://r-pkgs.org/index.html "],["template.html", "Chapter 15 Template chapter 15.1 Linking section 1 15.2 Overall goal of the chapter 15.3 Episode 1 (topic 1) 15.4 Episode 2 (topic 2) 15.5 Episode 3 (topic 3) 15.6 Further resources 15.7 Summary 15.8 Exercise solutions 15.9 Feedback 15.10 Putting into practice", " Chapter 15 Template chapter 15.1 Linking section 1 This initial section of each lesson (chapter) should build a link with the previous section of the book by providing a recap of what has been previously done. It will help with locating each chapter within the context of the entire book. 15.2 Overall goal of the chapter In this section we will describe what the overall aim of this chapter and target audience including: What they are already expected to know (their previous knowledge) What are the goals of the audience div.green { background-color:#e3ffd9; border-radius: 5px; padding: 20px;} Learning objectives What you will learn What you will be able to do at the end of this chapter What you will not learn & what to read instead Where to go from here List of episodes List of episodes in this chapter that will help achieve set goal with their short description and an explanation of links between them. Episode 1 Episode 2 Episode 3 15.3 Episode 1 (topic 1) Each episode developed within the chapter should contain a narrative to give a bit of a context and again demonstrate the target audience (if needed). Beyond it should provide episode-specific learning objectives and examples, which are to be intertwined with so-called self-check exercises which will allow the reader to assess his comprehension of the topic so far. div.purple { background-color:#e9d0f7; border-radius: 5px; padding: 20px;} Exercise 1: The exercise description to be in the coloured box & the small, control exercises should be placed at the end of the subsection. 15.4 Episode 2 (topic 2) div.yellow { background-color:#fff5e6; border-radius: 5px; padding: 20px;} Shortcut: Shortcuts to be in a yellow box. 15.5 Episode 3 (topic 3) 15.6 Further resources In this section we provide links to additional websites and sources that are useful in a given topic or package in the following way: R website Documentation pages 15.7 Summary This closing section should show the reader what has been done in this chapter and how it links with the topics provided in the next chapter by a brief introduction to next topic. 15.8 Exercise solutions Exercise 1 #code to exercise 1 only, results hidden Exercise 2 #code to exercise 2 only, results hidden 15.9 Feedback Feedback section aims at learning what was useful to the reader (learner) and what can be improved. It gives the reader an opportunity to reflect on what he/she learned and evaluate the book in this this context. 15.10 Putting into practice This final section is aimed at consolidating the knowledge and skills learned throughout the whole chapter, where the reader can put them into practice in a more complex working example with a new context. "]]