| Title: | Thematic Map Tools |
|---|---|
| Description: | Set of tools for reading and processing spatial data. The aim is to supply the workflow to create thematic maps. This package also facilitates 'tmap', the package for visualizing thematic maps. |
| Authors: | Martijn Tennekes [aut, cre] |
| Maintainer: | Martijn Tennekes <[email protected]> |
| License: | GPL-3 |
| Version: | 3.3-0.9000 |
| Built: | 2026-10-09 10:41:08 UTC |
| Source: | https://github.com/r-tmap/tmaptools |
This package offers a set of handy tool functions for reading and processing spatial data. The aim of these functions is to supply the workflow to create thematic maps, e.g. read shape files, set map projections, append data, calculate areas and distances, and query OpenStreetMap. The visualization of thematic maps can be done with the tmap package.
This page provides a brief overview of all package functions.
approx_areas
|
Approximate area sizes of polygons |
approx_distances
|
Approximate distances |
bb
|
Create, extract or modify a bounding box |
bb_poly
|
Convert bounding box to a polygon |
get_asp_ratio
|
Get the aspect ratio of a shape object |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
map_coloring
|
Find different colors for adjacent polygons |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
crop_shape
|
Crop shape objects |
simplify_shape
|
Simplify a shape |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
geocode_OSM
|
Get a location from an address description |
read_GPX
|
Read a GPX file |
read_osm
|
Read Open Street Map data |
rev_geocode_OSM
|
Get an address description from a location |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
Maintainer: Martijn Tennekes [email protected]
Authors:
Martijn Tennekes [email protected]
Useful links:
Report bugs at https://github.com/r-tmap/tmaptools/issues
Approximate the area sizes of the polygons in real-world area units (such as sq km or sq mi), proportional numbers, or normalized numbers. Also, the areas can be calibrated to a prespecified area total. This function is a convenient wrapper around st_area.
approx_areas(shp, target = "metric", total.area = NULL)approx_areas(shp, target = "metric", total.area = NULL)
shp |
shape object, i.e., an |
target |
target unit, one of
These units are the output units. See |
total.area |
total area size of |
Note that the method of determining areas is an approximation, since it depends on the used projection and the level of detail of the shape object. Projections with equal-area property are highly recommended. See https://en.wikipedia.org/wiki/List_of_map_projections for equal area world map projections.
Numeric vector of area sizes (class units).
if (require(tmap)) { data(NLD_muni) NLD_muni$area <- approx_areas(NLD_muni, total.area = 33893) tm_shape(NLD_muni) + tm_bubbles(size="area", size.legend = tm_legend(title = expression("Area in " * km^2))) # function that returns min, max, mean and sum of area values summary_areas <- function(x) { list(min_area=min(x), max_area=max(x), mean_area=mean(x), sum_area=sum(x)) } # area of the polygons summary_areas(approx_areas(NLD_muni)) # area of the polygons, adjusted corrected for a specified total area size summary_areas(approx_areas(NLD_muni, total.area=33893)) # proportional area of the polygons summary_areas(approx_areas(NLD_muni, target = "prop")) # area in squared miles summary_areas(approx_areas(NLD_muni, target = "mi mi")) # area of the polygons when unprojected summary_areas(approx_areas(sf::st_transform(NLD_muni, crs = 4326))) }if (require(tmap)) { data(NLD_muni) NLD_muni$area <- approx_areas(NLD_muni, total.area = 33893) tm_shape(NLD_muni) + tm_bubbles(size="area", size.legend = tm_legend(title = expression("Area in " * km^2))) # function that returns min, max, mean and sum of area values summary_areas <- function(x) { list(min_area=min(x), max_area=max(x), mean_area=mean(x), sum_area=sum(x)) } # area of the polygons summary_areas(approx_areas(NLD_muni)) # area of the polygons, adjusted corrected for a specified total area size summary_areas(approx_areas(NLD_muni, total.area=33893)) # proportional area of the polygons summary_areas(approx_areas(NLD_muni, target = "prop")) # area in squared miles summary_areas(approx_areas(NLD_muni, target = "mi mi")) # area of the polygons when unprojected summary_areas(approx_areas(sf::st_transform(NLD_muni, crs = 4326))) }
Approximate distances between two points or across the horizontal and vertical centerlines of a bounding box.
approx_distances(x, y = NULL, projection = NULL, target = NULL)approx_distances(x, y = NULL, projection = NULL, target = NULL)
x |
object that can be coerced to a bounding box with |
y |
a pair of coordintes, vector of two. Only required when |
projection |
projection code, needed in case |
target |
target unit, one of: |
If y is specifyed, a list of two: unit and dist. Else, a list of three: unit, hdist (horizontal distance) and vdist (vertical distance).
## Not run: if (require(tmap)) { data(NLD_prov) # North-South and East-West distances of the Netherlands approx_distances(NLD_prov) # Distance between Maastricht and Groningen p_maastricht <- geocode_OSM("Maastricht")$coords p_groningen <- geocode_OSM("Groningen")$coords approx_distances(p_maastricht, p_groningen, projection = 4326, target = "km") # Check distances in several projections sapply(c(3035, 28992, 4326), function(projection) { p_maastricht <- geocode_OSM("Maastricht", projection = projection)$coords p_groningen <- geocode_OSM("Groningen", projection = projection)$coords approx_distances(p_maastricht, p_groningen, projection = projection) }) } ## End(Not run)## Not run: if (require(tmap)) { data(NLD_prov) # North-South and East-West distances of the Netherlands approx_distances(NLD_prov) # Distance between Maastricht and Groningen p_maastricht <- geocode_OSM("Maastricht")$coords p_groningen <- geocode_OSM("Groningen")$coords approx_distances(p_maastricht, p_groningen, projection = 4326, target = "km") # Check distances in several projections sapply(c(3035, 28992, 4326), function(projection) { p_maastricht <- geocode_OSM("Maastricht", projection = projection)$coords p_groningen <- geocode_OSM("Groningen", projection = projection)$coords approx_distances(p_maastricht, p_groningen, projection = projection) }) } ## End(Not run)
Swiss army knife for bounding boxes. Modify an existing bounding box or create a new bounding box from scratch. See details.
bb( x = NA, ext = NULL, cx = NULL, cy = NULL, width = NULL, height = NULL, xlim = NULL, ylim = NULL, relative = FALSE, asp.target = NULL, asp.limit = NULL, current.projection = NULL, projection = NULL, output = c("bbox", "matrix", "extent") )bb( x = NA, ext = NULL, cx = NULL, cy = NULL, width = NULL, height = NULL, xlim = NULL, ylim = NULL, relative = FALSE, asp.target = NULL, asp.limit = NULL, current.projection = NULL, projection = NULL, output = c("bbox", "matrix", "extent") )
x |
One of the following:
. |
ext |
Extension factor of the bounding box. If 1, the bounding box is unchanged. Values smaller than 1 reduces the bounding box, and values larger than 1 enlarges the bounding box. This argument is a shortcut for both |
cx |
center x coordinate |
cy |
center y coordinate |
width |
width of the bounding box. These are either absolute or relative (depending on the argument |
height |
height of the bounding box. These are either absolute or relative (depending on the argument |
xlim |
limits of the x-axis. These are either absolute or relative (depending on the argument |
ylim |
limits of the y-axis. See |
relative |
boolean that determines whether relative values are used for |
asp.target |
target aspect ratio, which is width/height, of the returned bounding box. |
asp.limit |
maximum aspect ratio, which is width/height. Number greater than or equal to 1. For landscape bounding boxes, |
current.projection |
projection that corresponds to the bounding box specified by |
projection |
projection to transform the bounding box to. |
output |
output format of the bounding box, one of:
|
An existing bounding box (defined by x) can be modified as follows:
Using the extension factor ext.
Changing the width and height with width and height. The argument relavitve determines whether relative or absolute values are used.
Setting the x and y limits. The argument relavitve determines whether relative or absolute values are used.
A new bounding box can be created from scratch as follows:
Using the extension factor ext.
Setting the center coorinates cx and cy, together with the width and height.
Setting the x and y limits xlim and ylim
bounding box (see argument output)
if (require(tmap)) { ## load shapes data(NLD_muni) data(World) ## get bounding box (similar to sp's function bbox) bb(NLD_muni) ## extent it by factor 1.10 bb(NLD_muni, ext=1.10) ## double the width bb(NLD_muni, width=2, relative = TRUE) ## crop both dimensions from 0.25 to 0.75 bb(NLD_muni, xlim=c(.25, .75), ylim=c(.25, .75), relative = TRUE) ## extent it such that aspect ratio is 1 bb(NLD_muni, asp.target = 1) ## convert to longlat (EPSG 4326) bb(NLD_muni, projection=4326) } ## Not run: if (require(tmap)) { bb("Limburg", projection = 28992) bb_italy <- bb("Italy", projection = "+proj=eck4") tm_shape(World, bbox=bb_italy) + tm_polygons() # shorter alternative: tm_shape(World, bbox="Italy") + tm_polygons() } ## End(Not run)if (require(tmap)) { ## load shapes data(NLD_muni) data(World) ## get bounding box (similar to sp's function bbox) bb(NLD_muni) ## extent it by factor 1.10 bb(NLD_muni, ext=1.10) ## double the width bb(NLD_muni, width=2, relative = TRUE) ## crop both dimensions from 0.25 to 0.75 bb(NLD_muni, xlim=c(.25, .75), ylim=c(.25, .75), relative = TRUE) ## extent it such that aspect ratio is 1 bb(NLD_muni, asp.target = 1) ## convert to longlat (EPSG 4326) bb(NLD_muni, projection=4326) } ## Not run: if (require(tmap)) { bb("Limburg", projection = 28992) bb_italy <- bb("Italy", projection = "+proj=eck4") tm_shape(World, bbox=bb_italy) + tm_polygons() # shorter alternative: tm_shape(World, bbox="Italy") + tm_polygons() } ## End(Not run)
Convert bounding box to a spatial (sfc) object . Useful for plotting (see example). The function bb_earth returns a spatial polygon of the 'boundaries' of the earth, which can also be done in other projections (if a feasible solution exists).
bb_poly(x, steps = 100, stepsize = NA, projection = NULL) bb_earth( projection = NULL, stepsize = 1, earth.datum = 4326, bbx = c(-180, -90, 180, 90), buffer = 1e-06 )bb_poly(x, steps = 100, stepsize = NA, projection = NULL) bb_earth( projection = NULL, stepsize = 1, earth.datum = 4326, bbx = c(-180, -90, 180, 90), buffer = 1e-06 )
x |
object that can be coerced to a bounding box with |
steps |
number of intermediate points along the shortest edge of the bounding box. The number of intermediate points along the longest edge scales with the aspect ratio. These intermediate points are needed if the bounding box is plotted in another projection. |
stepsize |
stepsize in terms of coordinates (usually meters when the shape is projected and degrees of longlat coordinates are used). If specified, it overrules |
projection |
projection in which the coordinates of |
earth.datum |
Geodetic datum to determine the earth boundary. By default EPSG 4326. |
bbx |
boundig box of the earth in a vector of 4 values: min longitude, max longitude, min latitude, max latitude. By default |
buffer |
In order to determine feasible earth bounding boxes in other projections, a buffer is used to decrease the bounding box by a small margin (default |
sfc object
if (require(tmap) && packageVersion("tmap") >= "2.0") { data(NLD_muni) current.mode <- tmap_mode("view") qtm(bb_poly(NLD_muni)) # restore mode tmap_mode(current.mode) }if (require(tmap) && packageVersion("tmap") >= "2.0") { data(NLD_muni) current.mode <- tmap_mode("view") qtm(bb_poly(NLD_muni)) # restore mode tmap_mode(current.mode) }
Transpose quantitative variables to densitiy variables, which are often needed for choroplets. For example, the colors of a population density map should correspond population density counts rather than absolute population numbers.
calc_densities( shp, var, target = "metric", total.area = NULL, suffix = NA, drop = TRUE )calc_densities( shp, var, target = "metric", total.area = NULL, suffix = NA, drop = TRUE )
shp |
a shape object, i.e., an |
var |
name(s) of a qualtity variable name contained in the |
target |
the target unit, see |
total.area |
total area size of |
suffix |
character that is appended to the variable names. The resulting names are used as column names of the returned data.frame. By default, |
drop |
boolean that determines whether an one-column data-frame should be returned as a vector |
Vector or data.frame (depending on whether length(var)==1 with density values.
if (require(tmap) && packageVersion("tmap") >= "3.99") { data(NLD_muni) NLD_muni_pop_per_km2 <- calc_densities(NLD_muni, target = "km km", var = c("population", "dwelling_total")) NLD_muni <- sf::st_sf(data.frame(NLD_muni, NLD_muni_pop_per_km2)) tm_shape(NLD_muni) + tm_polygons( fill = c("population_km.2", "dwelling_total_km.2"), fill.legend = list( tm_legend(expression("Population per " * km^2)), tm_legend(expression("Dwellings per " * km^2)))) + tm_facets(free.scales = TRUE) + tm_layout(panel.show = FALSE) }if (require(tmap) && packageVersion("tmap") >= "3.99") { data(NLD_muni) NLD_muni_pop_per_km2 <- calc_densities(NLD_muni, target = "km km", var = c("population", "dwelling_total")) NLD_muni <- sf::st_sf(data.frame(NLD_muni, NLD_muni_pop_per_km2)) tm_shape(NLD_muni) + tm_polygons( fill = c("population_km.2", "dwelling_total_km.2"), fill.legend = list( tm_legend(expression("Population per " * km^2)), tm_legend(expression("Dwellings per " * km^2)))) + tm_facets(free.scales = TRUE) + tm_layout(panel.show = FALSE) }
Crop a shape object (from class sf, stars, sp, or raster). A shape file x is cropped, either by the bounding box of another shape y, or by y itself if it is a SpatialPolygons object and polygon = TRUE.
crop_shape(x, y, polygon = FALSE, ...)crop_shape(x, y, polygon = FALSE, ...)
x |
shape object, i.e. an object from class |
y |
bounding box, an |
polygon |
should |
... |
not used anymore |
This function is similar to crop from the raster package. The main difference is that crop_shape also allows to crop using a polygon instead of a rectangle.
cropped shape, in the same class as x
if (require(tmap) && packageVersion("tmap") >= "3.99") { data(World, NLD_muni, land, metro) #land_NLD <- crop_shape(land, NLD_muni) #qtm(land_NLD, raster="trees", style="natural") metro_Europe <- crop_shape(metro, World[World$continent == "Europe", ], polygon = TRUE) qtm(World) + tm_shape(metro_Europe) + tm_bubbles("pop2010", col="red", size.legend = tm_legend("European cities")) + tm_legend(frame=TRUE) }if (require(tmap) && packageVersion("tmap") >= "3.99") { data(World, NLD_muni, land, metro) #land_NLD <- crop_shape(land, NLD_muni) #qtm(land_NLD, raster="trees", style="natural") metro_Europe <- crop_shape(metro, World[World$continent == "Europe", ], polygon = TRUE) qtm(World) + tm_shape(metro_Europe) + tm_bubbles("pop2010", col="red", size.legend = tm_legend("European cities")) + tm_legend(frame=TRUE) }
Geocodes a location (based on a search query) to coordinates and a bounding box. Similar to geocode from the ggmap package. It uses OpenStreetMap Nominatim. For processing large amount of queries, please read the usage policy (https://operations.osmfoundation.org/policies/nominatim/).
geocode_OSM( q, projection = NULL, return.first.only = TRUE, keep.unfound = FALSE, details = FALSE, as.data.frame = NA, as.sf = FALSE, geometry = c("point", "bbox"), server = "https://nominatim.openstreetmap.org" )geocode_OSM( q, projection = NULL, return.first.only = TRUE, keep.unfound = FALSE, details = FALSE, as.data.frame = NA, as.sf = FALSE, geometry = c("point", "bbox"), server = "https://nominatim.openstreetmap.org" )
q |
a character (vector) that specifies a search query. For instance |
projection |
projection in which the coordinates and bounding box are returned. See |
return.first.only |
Only return the first result |
keep.unfound |
Keep list items / data.frame rows with |
details |
provide output details, other than the point coordinates and bounding box |
as.data.frame |
Return the output as a |
as.sf |
Return the output as |
geometry |
When |
server |
OpenStreetMap Nominatim server name. Could also be a local OSM Nominatim server. |
If as.sf then a sf object is returned. Else, if as.data.frame, then a data.frame is returned, else a list.
## Not run: if (require(tmap)) { geocode_OSM("India") geocode_OSM("CBS Weg 1, Heerlen") geocode_OSM("CBS Weg 1, Heerlen", projection = 28992) data(metro) # sample 5 cities from the metro dataset five_cities <- metro[sample(length(metro), 5), ] # obtain geocode locations from their long names five_cities_geocode <- geocode_OSM(five_cities$name_long, as.sf = TRUE) # change to interactive mode current.mode <- tmap_mode("view") # plot metro coordinates in red and geocode coordinates in blue # zoom in to see the differences tm_shape(five_cities) + tm_dots(col = "blue") + tm_shape(five_cities_geocode) + tm_dots(col = "red") # restore current mode tmap_mode(current.mode) } ## End(Not run)## Not run: if (require(tmap)) { geocode_OSM("India") geocode_OSM("CBS Weg 1, Heerlen") geocode_OSM("CBS Weg 1, Heerlen", projection = 28992) data(metro) # sample 5 cities from the metro dataset five_cities <- metro[sample(length(metro), 5), ] # obtain geocode locations from their long names five_cities_geocode <- geocode_OSM(five_cities$name_long, as.sf = TRUE) # change to interactive mode current.mode <- tmap_mode("view") # plot metro coordinates in red and geocode coordinates in blue # zoom in to see the differences tm_shape(five_cities) + tm_dots(col = "blue") + tm_shape(five_cities_geocode) + tm_dots(col = "red") # restore current mode tmap_mode(current.mode) } ## End(Not run)
Get the aspect ratio of a shape object, a tmap object, or a bounding box
get_asp_ratio(x, is.projected = NA, width = 700, height = 700, res = 100)get_asp_ratio(x, is.projected = NA, width = 700, height = 700, res = 100)
x |
A shape from class |
is.projected |
Logical that determined wether the coordinates of |
width |
See details; only applicable if |
height |
See details; only applicable if |
res |
See details; only applicable if |
The arguments width, height, and res are passed on to png. If x is a tmap object, a temporarily png image is created to calculate the aspect ratio of a tmap object. The default size of this image is 700 by 700 pixels at 100 dpi.
aspect ratio
if (require(tmap) && packageVersion("tmap") >= "2.0") { data(World) get_asp_ratio(World) get_asp_ratio(bb(World)) tm <- qtm(World) get_asp_ratio(tm) } ## Not run: get_asp_ratio("Germany") #note: bb("Germany") uses geocode_OSM("Germany") ## End(Not run)if (require(tmap) && packageVersion("tmap") >= "2.0") { data(World) get_asp_ratio(World) get_asp_ratio(bb(World)) tm <- qtm(World) get_asp_ratio(tm) } ## Not run: get_asp_ratio("Germany") #note: bb("Germany") uses geocode_OSM("Germany") ## End(Not run)
Get neighbours list from spatial objects. The output is similar to the function poly2nb of the spdep package with queen = FALSE, but uses sf instead of sp. Two polygons are considered neighbours only when their boundaries share a line segment (an edge), not merely a point.
get_neighbours(x)get_neighbours(x)
x |
a shape object, i.e., a |
A list where the items correspond to the features. Each item is a vector of neighbours.
Color the polygons of a map such that adjacent polygons have different colors. This function returns the color indices
map_coloring(x, algorithm = "dsatur", ncols = 8, permutation = 0, ...)map_coloring(x, algorithm = "dsatur", ncols = 8, permutation = 0, ...)
x |
Either a shape (i.e. a |
algorithm |
either |
ncols |
target number of colors, all of which are used about equally often. By default 8. Raised to 4 if set lower, and raised further, with a message, if more colors are needed for a valid coloring. |
permutation |
number that selects one of the many colorings a map has. By default 0. Any other whole number gives another one, so trying 1, 2, 3, ... is a way to look for a map that pleases. It changes both which polygons share a color and which color each group is given, and every permutation is equally valid and equally evenly spread. |
... |
to catch deprecated arguments |
As of tmaptools 3.3, the deprecated color functions get_brewer_pal and palette_explorer, have been removed. These have been replaced c4a and c4a_gui respectively from the package cols4all. Therefore, map_coloring will return color indices and will ignore the input arguments palette and contrast. See example.
Adjacency is determined by shared boundary lines (as in "rook" contiguity), not by shared points alone. This matters for e.g. Voronoi tessellations, where three or more cells can meet at a single vertex without actually sharing an edge; treating such point-touches as adjacency can force the use of unnecessarily many colors.
ncols is the target number of colors, with a minimum of 4 (the four-color theorem guarantees that 4 colors suffice for any planar map). All ncols of them are used, about equally often, so that no color dominates the map. Only when ncols colors are too few for a valid coloring is the number increased, in which case the user is informed via cli_inform. Use ncols = 4 for a map that uses as few colors as possible.
Evening out the colors is possible because a polygon may take any color that none of its neighbours has. So as long as one color is used at least two polygons more often than another, some polygon can be moved from the first to the second. A color that the coloring itself did not need is simply one that is used zero times, and is filled up the same way; this is what spreads a coloring that needs only 4 colors over all ncols of them.
A map has many colorings, and which one comes out is decided by choices between equally good options: which color a polygon is given, which polygon is moved to even out the colors, and which colors are handed to which group in the end. The argument permutation settles those choices, so that each number gives a different, equally valid map. Raise it until the map looks good.
As of tmaptools 3.4, the argument minimize has been removed: ncols now determines the number of colors on its own. The result no longer depends on the random seed, and the random number generator of the caller is left untouched, so that repeated plots of the same map keep the same colors. To go looking for a nicer looking map, vary permutation instead of the seed.
The "dsatur" algorithm first runs the DSatur heuristic (Brelaz, 1979), which colors the most constrained polygon at each step: the one with the largest number of distinct colors among its already colored neighbours, ties broken by the number of neighbours. Since this is a heuristic, it may fail even when a valid coloring exists; on maps of contiguous regions it typically needs one color more than necessary. It is therefore followed by a tabu search (Hertz and de Werra, 1987), which starts from a coloring that uses ncols colors but may have neighbours sharing one, and then repeatedly recolors a polygon involved in such a clash until none are left. Two reductions keep this cheap: polygons with fewer than ncols neighbours are set aside and colored last (a free color is then always available), and the rest are split into groups that are not connected to each other and searched separately. Use algorithm = "greedy" to skip the tabu search.
A vector of color indices.
Brelaz, D. (1979) New methods to color the vertices of a graph. Communications of the ACM 22(4), 251-256.
Hertz, A. and de Werra, D. (1987) Using tabu search techniques for graph coloring. Computing 39(4), 345-351.
if (require(tmap) && require(cols4all)) { data(World) ## using cols4all directly indices <- map_coloring(World) pal <- c4a("brewer.set2", n = max(indices)) World$color = pal[indices] tm_shape(World) + tm_polygons("color", fill.scale = tm_scale_asis()) + tm_crs("auto") # using map_coloring via "MAP_COLORS" in tmap tm_shape(World) + tm_polygons("MAP_COLORS", tm_scale(values = "brewer.set2")) + tm_crs("auto") # other example data(NLD_prov, NLD_muni) tm_shape(NLD_prov) + tm_fill("name", fill.legend = tm_legend_hide()) + tm_shape(NLD_muni) + tm_polygons("MAP_COLORS", fill_alpha = .25, fill.scale = tm_scale(values = "brewer.greys")) + tm_shape(NLD_prov) + tm_borders(lwd=2) + tm_text("name", options = opt_tm_text(shadow = TRUE)) + tm_title("Dutch provinces and\nmunicipalities", bg.color="white") }if (require(tmap) && require(cols4all)) { data(World) ## using cols4all directly indices <- map_coloring(World) pal <- c4a("brewer.set2", n = max(indices)) World$color = pal[indices] tm_shape(World) + tm_polygons("color", fill.scale = tm_scale_asis()) + tm_crs("auto") # using map_coloring via "MAP_COLORS" in tmap tm_shape(World) + tm_polygons("MAP_COLORS", tm_scale(values = "brewer.set2")) + tm_crs("auto") # other example data(NLD_prov, NLD_muni) tm_shape(NLD_prov) + tm_fill("name", fill.legend = tm_legend_hide()) + tm_shape(NLD_muni) + tm_polygons("MAP_COLORS", fill_alpha = .25, fill.scale = tm_scale(values = "brewer.greys")) + tm_shape(NLD_prov) + tm_borders(lwd=2) + tm_text("name", options = opt_tm_text(shadow = TRUE)) + tm_title("Dutch provinces and\nmunicipalities", bg.color="white") }
Read a GPX file. By default, it reads all possible GPX layers, and only returns shapes for layers that have any features.
read_GPX( file, layers = c("waypoints", "routes", "tracks", "route_points", "track_points"), remove.empty.layers = TRUE, as.sf = TRUE )read_GPX( file, layers = c("waypoints", "routes", "tracks", "route_points", "track_points"), remove.empty.layers = TRUE, as.sf = TRUE )
file |
a GPX filename (including directory) |
layers |
vector of GPX layers. Possible options are |
remove.empty.layers |
should empty layers (i.e. with 0 features) be removed from the list? |
as.sf |
not used anymore |
Note that this function returns sf objects, but still uses methods from sp and rgdal internally.
a list of sf objects, one for each layer
Read Open Street Map data. OSM tiles are read and returned as a spatial raster. Vectorized OSM data is not supported anymore (see details).
read_osm( x, zoom = NULL, type = "osm", minNumTiles = NULL, mergeTiles = NULL, use.colortable = FALSE, ... )read_osm( x, zoom = NULL, type = "osm", minNumTiles = NULL, mergeTiles = NULL, use.colortable = FALSE, ... )
x |
object that can be coerced to a bounding box with |
zoom |
passed on to |
type |
tile provider, by default |
minNumTiles |
passed on to |
mergeTiles |
passed on to |
use.colortable |
should the colors of the returned raster object be stored in a |
... |
arguments passed on to |
As of version 2.0, read_osm cannot be used to read vectorized OSM data anymore. The reason is that the package that was used under the hood, osmar, has some limitations and is not actively maintained anymore. Therefore, we recommend the package osmdata. Since this package is very user-friendly, there was no reason to use read_osm as a wrapper for reading vectorized OSM data.
The output of read_osm is a raster object.
## Not run: if (require(tmap)) { #### Choropleth with OSM background # load Netherlands shape data(NLD_muni) # read OSM raster data osm_NLD <- read_osm(NLD_muni, ext=1.1) # plot with regular tmap functions tm_shape(osm_NLD) + tm_rgb() + tm_shape(NLD_muni) + tm_polygons("population", convert2density=TRUE, style="kmeans", alpha=.7, palette="Purples") #### A close look at the building of Statistics Netherlands in Heerlen # create a bounding box around the CBS (Statistics Netherlands) building CBS_bb <- bb("CBS Weg 11, Heerlen", width=.003, height=.002) # read Microsoft Bing satellite and OpenCycleMap OSM layers CBS_osm1 <- read_osm(CBS_bb, type="bing") CBS_osm2 <- read_osm(CBS_bb, type="opencyclemap") # plot OSM raster data qtm(CBS_osm1) qtm(CBS_osm2) } ## End(Not run)## Not run: if (require(tmap)) { #### Choropleth with OSM background # load Netherlands shape data(NLD_muni) # read OSM raster data osm_NLD <- read_osm(NLD_muni, ext=1.1) # plot with regular tmap functions tm_shape(osm_NLD) + tm_rgb() + tm_shape(NLD_muni) + tm_polygons("population", convert2density=TRUE, style="kmeans", alpha=.7, palette="Purples") #### A close look at the building of Statistics Netherlands in Heerlen # create a bounding box around the CBS (Statistics Netherlands) building CBS_bb <- bb("CBS Weg 11, Heerlen", width=.003, height=.002) # read Microsoft Bing satellite and OpenCycleMap OSM layers CBS_osm1 <- read_osm(CBS_bb, type="bing") CBS_osm2 <- read_osm(CBS_bb, type="opencyclemap") # plot OSM raster data qtm(CBS_osm1) qtm(CBS_osm2) } ## End(Not run)
Reverse geocodes a location (based on spatial coordinates) to an address. It uses OpenStreetMap Nominatim. For processing large amount of queries, please read the usage policy (https://operations.osmfoundation.org/policies/nominatim/).
rev_geocode_OSM( x, y = NULL, zoom = NULL, projection = 4326, as.data.frame = NA, server = "https://nominatim.openstreetmap.org", params = NULL )rev_geocode_OSM( x, y = NULL, zoom = NULL, projection = 4326, as.data.frame = NA, server = "https://nominatim.openstreetmap.org", params = NULL )
x |
x coordinate(s), or a spatial points object ( |
y |
y coordinate(s) |
zoom |
zoom level |
projection |
projection in which the coordinates |
as.data.frame |
return as data.frame ( |
server |
OpenStreetMap Nominatim server name. Could also be a local OSM Nominatim server. |
params |
Additional parameters to pass to server. (must start with &), ex: "&accept-language=en" to return english rather than local language results. |
A data frame or a list with all attributes that are contained in the search result
## Not run: if (require(tmap)) { data(metro) # sample five cities from metro dataset set.seed(1234) five_cities <- metro[sample(length(metro), 5), ] # obtain reverse geocode address information addresses <- rev_geocode_OSM(five_cities, zoom = 6) five_cities <- sf::st_sf(data.frame(five_cities, addresses)) # change to interactive mode current.mode <- tmap_mode("view") tm_shape(five_cities) + tm_markers(text="name") # restore current mode tmap_mode(current.mode) } ## End(Not run)## Not run: if (require(tmap)) { data(metro) # sample five cities from metro dataset set.seed(1234) five_cities <- metro[sample(length(metro), 5), ] # obtain reverse geocode address information addresses <- rev_geocode_OSM(five_cities, zoom = 6) five_cities <- sf::st_sf(data.frame(five_cities, addresses)) # change to interactive mode current.mode <- tmap_mode("view") tm_shape(five_cities) + tm_markers(text="name") # restore current mode tmap_mode(current.mode) } ## End(Not run)
Simplify a shape consisting of polygons or lines. This can be useful for shapes that are too detailed for visualization, especially along natural borders such as coastlines and rivers. The number of coordinates is reduced.
simplify_shape(shp, fact = 0.1, keep.units = FALSE, keep.subunits = FALSE, ...)simplify_shape(shp, fact = 0.1, keep.units = FALSE, keep.subunits = FALSE, ...)
shp |
|
fact |
simplification factor, number between 0 and 1 (default is 0.1) |
keep.units |
prevent small polygon features from disappearing at high simplification (default FALSE) |
keep.subunits |
should multipart polygons be converted to singlepart polygons? This prevents small shapes from disappearing during simplification if keep.units = TRUE. Default FALSE |
... |
other arguments passed on to the underlying function |
This function is a wrapper of ms_simplify. In addition, the data is preserved. Also sf objects are supported.
sf object
## Not run: if (require(tmap)) { data(World) # show different simplification factors tm1 <- qtm(simplify_shape(World, fact = 0.05), title="Simplify 0.05") tm2 <- qtm(simplify_shape(World, fact = 0.1), title="Simplify 0.1") tm3 <- qtm(simplify_shape(World, fact = 0.2), title="Simplify 0.2") tm4 <- qtm(simplify_shape(World, fact = 0.5), title="Simplify 0.5") tmap_arrange(tm1, tm2, tm3, tm4) # show different options for keeping smaller (sub)units tm5 <- qtm(simplify_shape(World, keep.units = TRUE, keep.subunits = TRUE), title="Keep units and subunits") tm6 <- qtm(simplify_shape(World, keep.units = TRUE, keep.subunits = FALSE), title="Keep units, ignore small subunits") tm7 <- qtm(simplify_shape(World, keep.units = FALSE), title="Ignore small units and subunits") tmap_arrange(tm5, tm6, tm7) } ## End(Not run)## Not run: if (require(tmap)) { data(World) # show different simplification factors tm1 <- qtm(simplify_shape(World, fact = 0.05), title="Simplify 0.05") tm2 <- qtm(simplify_shape(World, fact = 0.1), title="Simplify 0.1") tm3 <- qtm(simplify_shape(World, fact = 0.2), title="Simplify 0.2") tm4 <- qtm(simplify_shape(World, fact = 0.5), title="Simplify 0.5") tmap_arrange(tm1, tm2, tm3, tm4) # show different options for keeping smaller (sub)units tm5 <- qtm(simplify_shape(World, keep.units = TRUE, keep.subunits = TRUE), title="Keep units and subunits") tm6 <- qtm(simplify_shape(World, keep.units = TRUE, keep.subunits = FALSE), title="Keep units, ignore small subunits") tm7 <- qtm(simplify_shape(World, keep.units = FALSE), title="Ignore small units and subunits") tmap_arrange(tm5, tm6, tm7) } ## End(Not run)