MULTIPOLYGON in the summary above refers to the geometry type of countries in the world object.
you can check out columns in the data frame:
worldnamelongworldgdpPercap
similar to regular data frames
summarize information in a column
summary(world$gdpPercap)
The sf package provides a plot() method for visualizing geographic data:
plot(world)
Note that instead of creating a single map, the plot() command has created multiple maps,
one for each variable in the world datasets.
This is useful for exploring the spatial distribution of different variables
plot a single feature on map:
plot(world['gdpPercap']) # GDP per capita
plot(world['lifeExp']) # life expectancy
plot a subset of the data
plot(world[3:6])
unique(world$continent)
plot population on a single continent
plot(world[world$continent=='Asia','pop'])
Plots are added as layers to existing images by setting add = TRUE.
We can plot the Asian continent over a map of the world.
Note that the first plot must only have one facet for add = TRUE to work.
If the first plot has a key, reset = FALSE must be used
world_asia <- world[world$continent == "Asia", ]
st_union return a single geometric object by combining several features; internal boundaries are ignored
asia <- st_union(world_asia)
asia
plot(world["pop"], reset = F) # reset = FALSE: keep the plot in a mode that allows adding further map elements
plot(asia, add = T, col = "red") # add = T: add more layers to the graph
sf’s plot method also has arguments specific to geographic data. e.g. expandBB
can be used plot an sf object in context: it takes a numeric vector of length four that expands the
bounding box of the plot relative to zero in the following order: bottom, left, top, right.
This is used to plot India in the context of its giant Asian neighbors,
with an emphasis on China to the east, in the following code chunk
now, select countries in Asia with populations larger than 100 mil
sel_area <- world %>% subset(continent == "Asia" & pop>=10^8)
plot(sel_area['pop'])
generate population average by continent
we'll use summaryBy from the doBy library
library(doBy)
st_drop_geometry removes the geometry column and leaves only the data frame
the geometry info can cause problems in data summary
dat <- data.frame(st_drop_geometry(world))
pop_ave <- summaryBy(pop ~ continent, data = dat, na.rm=T)
pop_ave
the operation can also be achieved by a pipe operator. here we simply create a column of
population average for each continent:
world %>%
st_drop_geometry() %>%
dplyr::group_by(continent) %>% # summarize population mean by continent groups
dplyr::summarize(pop = mean(pop, na.rm = TRUE))
additional attributes can be merged into the data from other sources
here we introduce the coffee production data
"coffee_data" from the spData package
??coffee_data
the coffee_data has 3 columns: name_long names major coffee-producing nations, coffee_production_2016
and coffee_production_2017 contain estimated values for coffee production in each year
now we join the continent population average and coffee data with world.
we also create a new variable of population density:
world2 <- world %>% dplyr::left_join(pop_ave, by='continent') %>%
dplyr::left_join(coffee_data, by='name_long') %>%
dplyr::mutate(pop_dens = pop / area_km2) # mutate creates a new column
names(world2)
notice the new column, pop_dens, is at the second to the last position.
the last column is reserved for geometric info.
plot population maps: continent population average, density
plot(world2["pop.mean"])
plot(world2["pop_dens"])
coffee production in 2017
plot(world2["coffee_production_2017"])
####################################
3. spatial operations
####################################
Spatial subsetting is the process of selecting features of a spatial object based on whether or not
they in some way relate in space to another object.
An example of spatial subsetting is provided by the nz and nz_height datasets in spData.
These contain the 16 main regions and 101 highest points in New Zealand
The following codes first creates an object representing Canterbury,
then uses spatial subsetting to return all high points in the region
plot(nz['Name'], col='white', reset=F, key.pos=NULL, main='') # omit color keys
plot(st_union(canterbury), col = 'red', add=T) # use st_union to consolidate the sf object. see above
plot(canterbury_height['elevation'], add=T) # add high points in Canterbury
suppose you want to find out the average height of high points in each region.
This is a good example of spatial aggregation: it is the geometry of the source
that defines how values in the target object are grouped.
to do this, you first join the nz data with height (nz_height),
then summarize average elevation by regional names.
The resulting objects have the same geometry as the aggregating object nz but
with a new column representing the average height of each region.
other summary functions such as median() and sd() can be used instead of mean()
group sequence
sample(c(1, 2, 3, 5, 6, 7, 8, 9, 10, 16, 23))
####################################
4. week 10 Assignment: Due on Sunday midnight
####################################
Task 3. Plot the population map of New Zealand, with colors for Marlborough, Auckland, and Gisborne only
Task 4. Show geographical centroids on New Zealand, with size proportional to log population/10.
color the map by median height of regions
To complete your assignment tasks, I'll provide you with R code snippets for both Task 3 and Task 4 based on the context provided earlier. You may need to adjust paths, file names, or specific details based on your environment or data source if needed. The previous explanations gave you a solid foundation, so let's dive into these specific tasks.
Task 3: Plot the Population Map of New Zealand, Highlighting Marlborough, Auckland, and Gisborne
library(sf)
library(dplyr)
library(spData)
# Loading the New Zealand data
data("nz")
# Highlighting regions Marlborough, Auckland, and Gisborne using a new column for color
nz$highlight <- ifelse(nz$Name %in% c("Marlborough", "Auckland", "Gisborne"), "highlight", "normal")
# Plotting the map
plot(nz["highlight"],
col = c("gray", "blue")[factor(nz$highlight)], # Setting colors
main = "Population Map of New Zealand (Highlighted: Marlborough, Auckland, Gisborne)",
key.pos = NULL) # Removing the legend since it's straightforward
Task 4: Show Geographical Centroids on New Zealand, Size Proportional to log(Population)/10 and Color Map by Median Height of Regions
# Assuming nz_height is already loaded/available and contains the "population" column.
# Otherwise, adjust accordingly based on your dataset.
# Calculating region centroids with size proportional to log population
nz_centroids <- st_centroid(nz, of_largest_polygon = TRUE)
nz$centroid_pop_size <- log(nz$pop / 10) # Assuming 'pop' is a population attribute
# Joining nz_height to obtain height and calculating median height for color
nz_height_joined <- st_join(nz, nz_height)
# Calculating median elevation by region
nz$median_elevation <- nz_height_joined %>%
group_by(Name) %>%
summarise(median_elevation = median(elevation, na.rm = TRUE)) %>%
.$median_elevation # Extracting the median_elevation column
# Setting color scale for median height
col_fun <- colorRampPalette(c("white", "green", "brown"))
# Plotting the base map colored by median elevation
plot(nz["median_elevation"], col = col_fun(100),
main = "New Zealand: Centroids by Log Population, Color by Median Elevation",
key.pos = 4, # Positioning the legend
reset = FALSE) # Prepare for adding layers
# Adding centroids sized by log(population) and applying a universal color for visibility
points(st_geometry(nz_centroids), pch = 20, cex = nz$centroid_pop_size, col = "red")
These snippets should achieve Task 3 and Task 4 based on your coursework requirements. Make sure to review the details such as the presence of population data or the specifications for calculating the spatial aggregations and adapt the code if necessary. The colorRampPalette() function and its parameters can be adjusted to refine your map's color scheme further.