| Title: | Draw Geographical Maps |
| Version: | 3.4.3 |
| Date: | 2025-05-15 |
| Description: | Display of maps. Projection code and larger maps are in separate packages ('mapproj' and 'mapdata'). |
| Depends: | R (≥ 3.5.0) |
| Imports: | graphics, utils |
| LazyData: | yes |
| Suggests: | mapproj (≥ 1.2-0), mapdata (≥ 2.3.0), sf, rnaturalearth |
| License: | GPL-2 |
| URL: | https://github.com/adeckmyn/maps |
| BugReports: | https://github.com/adeckmyn/maps/issues |
| NeedsCompilation: | yes |
| Repository: | CRAN |
| Packaged: | 2025-05-19 08:35:55 UTC; alex |
| Author: | Richard A. Becker [aut] (Original S code), Allan R. Wilks [aut] (Original S code), Ray Brownrigg [trl, aut] (R version), Thomas P. Minka [aut] (Enhancements), Alex Deckmyn |
| Maintainer: | Alex Deckmyn <alex.deckmyn@meteo.be> |
| Date/Publication: | 2025-05-26 17:40:02 UTC |
Read sf, SpatialPolygons and SpatialLines objects
Description
These functions transform some classes provided by the packagessp andsf into a simple list that can be used by map().
Usage
SpatialPolygons2map(database, namefield=NULL)SpatialLines2map(database, namefield=NULL) sf2map(database, namefield="name")Arguments
database | A |
namefield | The name of a data column in |
Details
The 'map' list object only preserves co-ordinates and polygon names. All other information available in the original data is lost. For instance, plotting order for enclaves may be wrong, resulting in invisible polygons when settingfill=TRUE.
The optionnamefield is only taken into account ifdatabase is classSpatial[]DataFrame.namefield may be a vector of column names, e.g. to get polygons named as 'country:state'.
Value
A list with four components:x, y, names, range, similar to the return value ofmap(). This data can be used as a database formap(). The lines and polygons are separated by NA.
See Also
map,SpatialPolygons (in thesp library).
Area of projected map regions
Description
Computes the areas of regions in a projected map.
Usage
area.map(m, regions = ".", sqmi=TRUE, ...)Arguments
m | a map object containing named polygons (created with |
regions | a character vector naming one of more regions, as in |
sqmi | If |
... | additional arguments to |
Details
The area of each matching region in the map is computed, andregions which match the same element ofregions have theirareas combined. Each region is assumed planar, with verticesspecified by thex andy components of the map object.
The correct use of this function is to first usemap tocreate polygons and project the coordinates onto a plane, then applyarea.map to compute the area of the projected regions.If the projection is area-preserving (such asalbers),then these areas will match the area on the globe, up to aconstant. To get an absolute area in square miles, thesqmioption will scale the result, depending on the projection.
The coordinates frommap are affected by itsresolution argument, so useresolution=0 for the mostaccurate areas.
Value
a named vector of region areas.
NOTE
Thesqmi option assumes the coordinates have been projectedwith themapproject function.
Author(s)
Tom Minka
See Also
area.polygon,apply.polygon
Examples
# because the projection is rectangular, these are not true areas on the globe.m = map("state", fill = TRUE, plot = FALSE)area.map(m)area.map(m, ".*dakota")area.map(m, c("North Dakota", "South Dakota"))if(require(mapproj)) { # true areas on the globe m = map("state", proj="bonne", param=45, fill=TRUE, plot=FALSE) # North Dakota is listed as 70,704 square miles area.map(m, "North Dakota")}Database of Canadian cities
Description
This database is of Canadian cities of population greater than about 1,000.Also included are province capitals of any population size.
Format
A list with 6 components, namely "name", "country.etc", "pop", "lat","long", and "capital", containing the city name, the provinceabbreviation, approximate population (as at January 2006), latitude,longitude and capital status indication (0 for non-capital, 1 forcapital, 2 for provincial
capital.
NOTE
Some of the city names may be out of date. Please sendany corrections to the package maintainer.
See Also
United States County Map
Description
This database produces a map of the counties of the United States mainlandgenerated from US Department of the Census data (see the reference).
Usage
data(countyMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
US Department of Commerce, Census Bureau,County Boundary File,computer tape, available from Customer Services,Bureau of the Census, Washingdon DC 20233.
See Also
map.
Examples
map('county', 'iowa', fill = TRUE, col = palette())FIPS county codes for US County Map
Description
A database matching FIPS codes to maps package county and state names.
Usage
data(county.fips)Format
A list with 2 components, namely "fips" and "polyname", containing theFIPS number and respective state or county polygon name. Note that "fips" is represented as an integer, so any leading zero (which is part of the fips code) is not shown by default.
See Also
France Map
Description
This france database comes from the NUTS III (Tertiary AdministrativeUnits of the European Community) database of the United NationsEnvironment Programme (UNEP) GRID-Geneva data sets. These were preparedaround 1989, and so may be somewhat out of date.
Users of data sets supplied through UNEP/GRID are requested toincorporate in output products and reports acknowledgements to theoriginator of the data and to the fact that they were acquired throughUNEP/GRID. Appropriate wording may be "UNESCO (1987) throughUNEP/GRID-Geneva".
Usage
data(franceMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
Details
This map database can now easily be replaced by data taken directly from free sources, e.g. Natural Earth (see example).
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
See Also
Examples
map('france', fill = TRUE, col = 1:10)# replace by a public domain map at higher resolution:# fr1 <- rnaturalearth::ne_states("france")# this still includes overseas domains, so we remove those:# france2 <- map(fr1, xlim=c(-20, 20), ylim=c(30, 60), lforce="e",# fill=TRUE, plot=FALSE)Identify regions on a map
Description
Identifies the map regions clicked by the user.
Usage
## S3 method for class 'map'identify(x, n = 1, index = FALSE, ...)Arguments
x | a map object containing named polygons. |
n | the number of clicks to wait for. |
index | If TRUE, returns the index of the polygon, rather thanits name. |
... | additional arguments passed to |
Details
The current algorithm is somewhat crude — selects the region whosecentroid is closest to the click. A more sophisticated approach wouldusemap.where.
Value
a character vector of lengthn, naming the selected regions.
Author(s)
Tom Minka
See Also
Examples
identify(map("state", fill = TRUE, col = 0))if(require(mapproj)) identify(map("world", proj = "lagrange", fill = TRUE, col = 0, wrap=c(-180,180,-90)))Internally Required Functions
Description
These functions are called internally and will generally not berequired by the user.
Usage
makepoly(xy, gonsize, keep)mapgetg(database, gons, fill, xlim, ylim)mapgetl(database, lines, xlim, ylim, fill)mapname(database, patterns, exact)mapthin(xy, delta, symmetric)maptype(database)Internally Required Functions
Description
These functions are called internally and will generally not berequired by the user.
Usage
char.to.ascii(s)is.regexp(s)indicators.factor(y)insert(x, i, v)match.map.slow(nam, regions, warn = FALSE)match.map.grep(nam, regions, warn = FALSE)map.poly(database, regions = ".", exact = FALSE, xlim = NULL, ylim = NULL, boundary = TRUE, interior = TRUE, fill = FALSE, as.polygon = FALSE, namefield="name")map.wrap(p, xlim=NULL)map.wrap.poly(data, xlim, poly = FALSE, antarctica = -89.5)map.clip.poly(data, xlim = c(NA, NA), ylim = c(NA, NA), poly = FALSE)subgroup(x, i)gp.smooth(x, z, xo, lambda, r)kernel.smooth(x, z, xo, lambda, region = NULL, normalize = TRUE)kernel.region.region(x, region, lambda)kernel.region.x(x, region, z, lambda).map.range(new)Identify countries by ISO 3166 codes (2 or 3 letters) or by Sovereignty.
Description
This data set and the simple look-up functions allow to build lists of counrtries for the world map.
Usage
iso.expand(a, regex=TRUE)sov.expand(sov, regex=TRUE) iso.alpha(x, n=2)Arguments
a | A vector of ISO codes. All elements should have the same length, either 2 or 3 letters. Not case sensitive. |
sov | A vector of country names. The result is a list of all countries that fall under their sovereignty. Case sensitive, must fit completeley. |
regex | If TRUE (default), the return vector has the same length as the input ( |
x | Vector of country names, may include colons. |
n | An integer identitying which ISO code is required. Allowed values are 2 and 3. |
Details
The ISO 3166-1 standard identifies countries by a 2 and 3 letter codes.iso.expand translates these codes into the country names as used by theworld data base.iso.alpha does the reverse. Some countries have different ISO codes for different regions (e.g. China:Hong Kong has ISO code HK). In such cases,iso.alpha will return the main code, butiso.expand will return a regular expression that excludes some parts.
Value
iso.expand returns vector of country names. When used as input formap it will plot all the countries as identified either by their sovereignty or by ISO codes. Ifregex=FALSE the length of the vector may be shorter or longer than the input. Ifregex=TRUE, the results are concatenated in regular expressions. This format is less readable, but can be used as input e.g. formatch.map.iso.alpha always returns a vector of the same length as the input, containing the 2- or 3-letter codes.
NOTE
These functions use regular expressions and the results will often not work well withmap(...,exact=TRUE).
References
https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
See Also
Examples
# France and all its overseas departments, territories etc.sov.expand("France") # France and all its overseas departments, territories etc.# Canary Islands are not included in map("Spain")iso.expand("ES")map(regions=sov.expand("Spain"))# draw a map with ISO codes as labels:wm <- map("world", fill=TRUE, col=0, xlim=c(-10,40), ylim=c(30,60))# take out islands, but you loose e.g. UK, New Zealand, small island statesnam <- grep(":", wm$names, inv=TRUE, val=TRUE)# ad ISO codes as labelmap.text(wm, regions=nam, label=iso.alpha(nam), col=2, exact=TRUE, add=TRUE)ISO 3166 country codes (2 or 3 letters) and sovereignty.
Description
This data set lists all ISO3166 country codes and the sovereignty for each country in the list. Some entries are regular expressions.
Format
A data frame with 5 columns: "a2", "a3", "name", "mapname", "sovereignty". These contain the 2- and 3-letter ISO code, the official name, the (possibly shorter) name used in the map data base, and the sovereign country.
Details
The ISO 3166-1 standard identifies countries by a 2 and 3 letter codes. This table listst these for all countries on the world map. This data set also serves as basis for the function iso.expand() and its siblings.
NOTE
Some countries have different ISO codes for some regions. To deal with such particular cases, the "mapname" column may sometimes contain (perl-style) regular expressions rather than simply a country name. For instance, "FI" has mapname "Finland(?!:Aland)", because the Aland islands have a different ISO code. Other codes may appear in two rows if certain parts of countries are not written with the main country as base name. Usually, that is for compatibility with the legacy world data base.
References
https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
See Also
Italy Map
Description
This italy database comes from the NUTS III (Tertiary AdministrativeUnits of the European Community) database of the United NationsEnvironment Programme (UNEP) GRID-Geneva data sets. These were preparedaround 1989, and so may be somewhat out of date.
Users of data sets supplied through UNEP/GRID are requested toincorporate in output products and reports acknowledgements to theoriginator of the data and to the fact that they were acquired throughUNEP/GRID. Appropriate wording may be "UNESCO (1987) throughUNEP/GRID-Geneva".
Usage
data(italyMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
See Also
Examples
map('italy', fill = TRUE, col = 1:10)World lakes database
Description
This database contains a selection of large lakes (and islands within) taken from the Natural Earth 1:50m map, the same data source as the (v3.0) world map. The lake boundaries are consistent with the 'world' database.
Usage
data(lakesMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
Source
The data in this data base is derived from the public domain GIS project Natural Earth, the file "ne_50m_lakes". The Natural Earth data set is available fromhttps://www.naturalearthdata.com.
References
Natural Earth projecthttps://www.naturalearthdata.com
See Also
map.
Examples
map('world')map('lakes', add=TRUE, fill=TRUE, col='white', boundary='black')Draw Geographical Maps
Description
Draw lines and polygons as specified by a map database.
Usage
map(database = "world", regions = ".", exact = FALSE, boundary = TRUE, interior = TRUE, projection = "", parameters = NULL, orientation = NULL, fill = FALSE, col = 1, plot = TRUE, add = FALSE, namesonly = FALSE, xlim = NULL, ylim = NULL, wrap = FALSE, resolution = if (plot) 1 else 0, type = "l", bg = par("bg"), mar = c(4.1, 4.1, par("mar")[3], 0.1), myborder = 0.01, namefield="name", lforce="n", ...)Arguments
database | character string naming a geographical database, a list of |
regions | character vector that names the polygons to draw.Each database is composed of a collection of polygons, and each polygon hasa unique name.When a region is composed of more than one polygon, the individual polygonshave the name of the region, followed by a colon and a qualifier,as in |
exact | If |
boundary | If |
interior | If |
projection | character string that names a map projection to use.See |
parameters | numeric vector of parameters for use with the |
orientation | a vector |
fill | logical flag that says whether to draw lines or fill areas.If |
col | vector of colors.If |
plot | logical flag that specifies whether plottingshould be done.If |
add | logical flag that specifies whether to add to thecurrent plot.If |
namesonly | If |
xlim | two element numericvector giving a range of longitudes, expressedin degrees, to which drawingshould be restricted.Longitude is measured in degrees east of Greenwich, so that, in particular,locations in the USA have negative longitude.If |
ylim | two element numeric vector giving a range of latitudes,expressed in degrees, to which drawingshould be restricted.Latitude is measured in degrees north of theequator, so that, in particular,locations in the USA have positive latitude.If |
wrap | Boolean or a numeric vector. If TRUE, lines that cross too far across the map(due to a strange projection) are omitted. If wrap is a vector of length 2 or more, it is interpreted as the longitude range to be used for a global map, e.g. |
resolution | number that specifies the resolution with whichto draw the map.Resolution 0 is the full resolution of the database.Otherwise, just before polylines are plotted they are thinned:roughly speaking, successive points on the polyline that arewithin |
type | character string that controls drawing of the map.Aside from the default |
bg | background color. |
mar | margins, as in |
myborder | scalar or vector of length 2 specifying the porportion of the plotto add to the defined or computed limits as borders. |
namefield | A vector of column names to be used as region name if |
lforce | Limit enforcement. Only taken into account if |
... | Extra arguments passed to |
Details
The simplest form of use of this function is:
map(mymap)
wheremymap is the returned value from a previous call tomap().
Value
Ifplot = TRUE, a plot is made where the polygons selected fromdatabase, through theregions,xlim, andylim arguments, are outlined(fill isFALSE) or filled (fill isTRUE)with the colors incol.
The return value is a list withx,y,range, andnames components. This object can be used as adatabase for successive callstomap and functions.Iffill isFALSE, thex andy vectors arethe coordinates of successive polylines, separated byNAs. Iffill isTRUE, thex andy vectors havecoordinates of successive polygons, again separated byNAs.Thus the return value can be handed directly tolines orpolygon, as appropriate.
Whennamesonly isTRUE, only the names component is returned.
After a call tomap for which theprojection argument wasspecified there will be a global variable.Last.projectioncontaining information about the projection used.This will be consulted in subsequent calls tomap which useprojection = ''.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.https://web.archive.org/web/20050825145143/http://www.research.att.com/areas/stat/doc/93.2.ps
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.https://web.archive.org/web/20050825145143/http://www.research.att.com/areas/stat/doc/95.2.ps
See Also
map.text,map.axes,map.scale,map.grid (in themapproj library),polygon,SpatialPolygons2map
Examples
map()# low resolution map of the worldmap(wrap = c(0,360), fill = TRUE, col = 2) # pacific-centered map of the worldmap(wrap = c(0, 360, NA), fill = TRUE, col = 2) # idem, without Antarcticamap('usa')# national boundariesmap('county', 'new jersey')# county map of New Jerseymap('state', region = c('new york', 'new jersey', 'penn'))# map of three statesmap("state", ".*dakota", myborder = 0)# map of the dakotasmap.axes()# show the effect of myborder = 0if(require(mapproj)) map('state', proj = 'bonne', param = 45)# Bonne equal-area projection of states# names of the San Juan islands in Washington statemap('county', 'washington,san', names = TRUE, plot = FALSE)# national boundaries in one linetype, states in another# (figure 5 in the reference)map("state", interior = FALSE)map("state", boundary = FALSE, lty = 2, add = TRUE)# plot the ozone data on a base map# (figure 4 in the reference)data(ozone)map("state", xlim = range(ozone$x), ylim = range(ozone$y))text(ozone$x, ozone$y, ozone$median)box()if(require(mapproj)) {# mapproj is used for projection="polyconic" # color US county map by 2009 unemployment rate # match counties to map using FIPS county codes # Based on J's solution to the "Choropleth Challenge" # http://blog.revolutionanalytics.com/2009/11/choropleth-challenge-result.html # load data # unemp includes data for some counties not on the "lower 48 states" county # map, such as those in Alaska, Hawaii, Puerto Rico, and some tiny Virginia # cities data(unemp) data(county.fips) # define color buckets colors = c("#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043") unemp$colorBuckets <- as.numeric(cut(unemp$unemp, c(0, 2, 4, 6, 8, 10, 100))) leg.txt <- c("<2%", "2-4%", "4-6%", "6-8%", "8-10%", ">10%") # align data with map definitions by (partial) matching state,county # names, which include multiple polygons for some counties cnty.fips <- county.fips$fips[match(map("county", plot=FALSE)$names, county.fips$polyname)] colorsmatched <- unemp$colorBuckets [match(cnty.fips, unemp$fips)] # draw map map("county", col = colors[colorsmatched], fill = TRUE, resolution = 0, lty = 0, projection = "polyconic") map("state", col = "white", fill = FALSE, add = TRUE, lty = 1, lwd = 0.2, projection="polyconic") title("unemployment by county, 2009") legend("topright", leg.txt, horiz = TRUE, fill = colors) # Choropleth Challenge example, based on J's solution, see: # http://blog.revolutionanalytics.com/2009/11/choropleth-challenge-result.html # To see the faint county boundaries, use RGui menu: File/SaveAs/PDF}Draw Axes on Geographical Maps
Description
Draws a set of axes on an existing map.
Usage
map.axes(...)Arguments
... | Extra arguments passed to |
Side Effects
x- and y-axes are drawn for the currently displayed map. These willdisplay in longitude and latitude (if no projection= has beenspecified in the map() call).
Examples
map("state")map.axes(cex.axis=0.8)Add Cities to Existing Map
Description
Adds city locations and (optionally) names to an existing map using aspecified database.
Usage
map.cities(x = world.cities, country = "", label = NULL, minpop = 0,maxpop = Inf, capitals = 0, cex = par("cex"), projection = FALSE,parameters = NULL, orientation = NULL, pch = 1, ...)Arguments
x | Name of database. See |
country | If the string country is specified, limit the displayed cities to befrom within the specified country, province or state (depending on howthe database has been constructed). |
label | If |
minpop | The minimum value of population below which a particular city will notbe shown. |
maxpop | The maximum value of population above which a particular city will notbe shown. |
capitals | Selection of capitals-only display. Capitals may be 1 (country capital),2 (provincial, state, or regional capital) or 3 (local capital). See |
cex | The value of cex acts to override the current value of character sizeexpansion. |
projection | Boolean or character value. If |
parameters | numeric vector of parameters for use with the |
orientation | a vector |
pch | plotting character to use for marking city location. See |
... | Further plotting parameters may be specified as for the commands |
Details
The database is searched for all cities matching the specified criteriaand fitting within the limits of the plot currently displayed. Thedefault database is of all cities that have a population greater than acertain threshold or which are capital cities of a country or islandterritory. The threshold varies from country to country, but ingeneral is no higher than about 40,000. The data were originally obtained from Stefan Helders' website (http://www.world-gazetteer.com), which no longer exists. There are no recent updates available.
There are three supplied databases, world.cities (the default), us.citiesand canada.cities. The latter two, which need to be made available byusing a'data()' call, include the state or province name with thecity name (thanks to John Woodruffjpwoodruff@irisinternet.netfor the state and province information).
Note that if the underlying map is "Pacific-centric", i.e. longitudesexceed 180 degrees, and a projection is used, then the map.cities datamust be transformed appropriately.
Value
No value is returned from map.cities.
Side Effects
All cities within the boundaries of the plot containing the current mapare added to the plot. Note that it is possible that the boundaries ofthe plot exceed the boundaries of the map requested, and so more citiesthan were expected might be shown.
See Also
world.cities,canada.cities,us.cities
Examples
map("world", "China")map.cities(country = "China", capitals = 2)map("state", "New Jersey")data(us.cities)map.cities(us.cities, country="NJ")Add Scale to Existing Unprojected Map
Description
Adds a scale to an existing map, both as a ratio and a distance gauge.
Usage
map.scale(x, y, relwidth = 0.15, metric = TRUE, ratio = TRUE, ...)Arguments
x | Horizontal location of left end of distance gauge. If not specified,this will be taken to be near the lower left corner of the map. |
y | Vertical location of left end of distance gauge. If not specified,this will be taken to be near the lower left corner of the map. |
relwidth | Proportion of width of display to be used for the scale. The default is0.15 (15%). |
metric | If |
ratio | If |
... | Further plotting parameters may be specified as for the command text(). |
Details
The scale is calculated from the displayed graph's plotting parameters,and the latitude of the location at which the distance gauge will bedisplayed.
Value
The exact calculated scale is returned.
NOTE
This function is meaningful only if no projection= has been specifiedin the call to map().
Side Effects
A scale is added to the currently displayed map. This takes the form ofan approximate 1:n scale (containing 2-3 significant digits), above adistance gauge which is reasonably accurate for the latitude at which itappears. The circumference at the given latitude is interpolated from aradius of 6356.78 km at the pole and 6378.16 km at the equator.
See Also
Examples
map("world", "China")map.scale()Draw a map with labeled regions
Description
Likemap, but labels the regions.
Usage
map.text(database, regions = ".", exact = FALSE, labels, cex = 0.75,add = FALSE, move = FALSE, ...)Arguments
database | character string naming a geographical database, or a list of |
regions | character vector that names the polygons to draw. |
exact | If 'TRUE', only exact matches with 'regions' are selectedfor drawing. |
labels | character vector of labels, one for each regionselected. Defaults to the names in the database. |
cex | character expansion factor. |
add | If |
move | If |
... | Other arguments are the same as in |
Value
Ifadd = FALSE, a map is drawn by callingmap.Then the label for each region is placed at the centroid of the regionpolygon.
The return value is a map object, as frommap.
Author(s)
Tom Minka
Examples
map.text("world", "ira") # iran and iraqmap.text("state", "penn")map.text("county", "penn") # Pennsylvania countiesmap.text("county", "new jersey") # New Jersey countiesLocate points on a map
Description
Returns the region names containing given locations.
Usage
map.where(database = "world", x, y, ...)Arguments
database | character string naming a geographical database, or a list of |
x | vector of longitudes. |
y | vector of latitudes. |
... | Options for |
.
Value
A list of character strings, naming the map region that each(longitude, latitude) pair falls into.
Note
For points close to a border (polygon boundary), the result may be wrong if theresolution of the database is insufficient.This function may also give erroneous results if the database containsenclaves. For instance, a point in San Marino may also be identified as being in Italy.
Author(s)
Tom Minka
See Also
in.polygon
Examples
# NYCmap.where("state", -73.8, 41)# Aucklandmap.where("nz", 174.6, -36.92)# find both in the worldmap.where(x = c(174.6, -73.8), y = c(-36.92, 41))# with a map object:m = map("state", "new york", fill = TRUE, plot = FALSE)map.where(m, -73.8, 41)Index map regions
Description
Assigns an index to each map region, useful for map coloring.
Usage
match.map(database, regions, exact = FALSE, warn = TRUE)Arguments
database | character string naming a geographical database, or a map object.See the documentation for |
regions | a vector of names, or more generally regular expressionsto match against the map region names. |
exact | If |
warn | If |
Value
Returns an integer vector giving an index to each region in the database.The index is the index of the string inregions which matches theregion name. Matching is done as inmap.More specifically, all regionsr whose name matchesregions[i] will have indexi.Unmatched regions will have indexNA.Overlapping matches cause an error.
This behavior differs frompmatch because a single entryinregions may match several entries in the map.
Author(s)
Tom Minka
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report, 1991.
See Also
Examples
# filled map showing Republican vote in 1900# (figure 6 in the reference)data(state, package = "datasets")data(votes.repub)state.to.map <- match.map("state", state.name)x <- votes.repub[state.to.map, "1900"]gray.colors <- function(n) gray(rev(0:(n - 1))/n)color <- gray.colors(100)[floor(x)]map("state", fill = TRUE, col = color); map("state", add = TRUE)New Zealand Basic Map
Description
This database produce a map of New Zealand at a basic level ofdetail. The ‘"nz"’ database includes the 3 main Islands and 19 smallercoastal islands.
Usage
data(nzMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
See Also
Examples
map('nz')map('nz', xlim = c(166, 179), ylim = c(-48, -34))Sample datasets
Description
Datasets used to illustrate map functions.
ozone contains the median of daily maxima ozone concentration in 41 US cities for June 1974 through August 1974. Concentrations are in parts per billion (ppb).
unemp Has population and unemployment percentage for US counties.
votes.repub contains the percentage republican votes in the 1900 election.
Usage
data(ozone)data(unemp)data(votes.repub)References
Cleveland, W.S., Kleiner, B., McRae, J.E., Warner, J.L., and Pasceri, P.E. ,"The Analysis of Ground-Level Ozone Data from New Jersey, New York, Connecticut, and Massachusetts: Data Quality Assessment and Temporal and Geographical Properties",Bell Laboratories Memorandum, 1975.
Polygon functions
Description
These functions are called internally and will generally not berequired by the user.
Usage
area.polygon(p)centroid.polygon(p)## S3 method for class 'polygon'as.matrix(x, ...)closed.polygon(p)in.one.polygon(p, x)in.polygon(p, x)num.polygons(p)sub.polygon(p, i)Smooth out aggregated data
Description
Increases the resolution of data aggregated over map regions,by either smoothing or interpolation.Also fills in missing values.
Usage
smooth.map(m, z, res = 50, span = 1/10, averages = FALSE, type = c("smooth","interp"), merge = FALSE)Arguments
m | a map object |
z | a named vector |
res | a vector of length two, specifying the resolution of thesampling grid ineach dimension. If a single number, it is taken as the verticalresolution, with double taken as the horizontal resolution. |
span | kernel parameter (larger = smoother). |
averages | If |
type | see details. |
merge | If |
Details
Fortype = "smooth", the region totals are first convertedinto point measurements on thesampling grid, by dividing the total for a region among all samplepoints inside it. Then it is a regular kernel smoothing problem. Note that the region totals are not preserved.
The predictionz_o forlocationx_o (a vector) is the average ofz fornearby sample points:
z_o = \frac{\sum_x k(x, x_o) z(x)}{\sum_x k(x, x_o)}
k(x, x_o) = exp(-\lambda ||x - x_o||^2)
\lambda is determined fromspan.Note thatx_o is over the same sampling grid asx, butz_o is not necessarily the same asz(x_o).
Fortype = "interp", the region totals are preserved by thehigher-resolution function.The function is assumed to come from aGaussian process with kernelk. The measurementz[r]is assumed to be the sum of the function over the discrete samplepoints inside regionr.This leads to a simple formula for the covariance matrix ofzand the cross-covariance betweenzo andz.The prediction is the cross-covariance times the inverse covariancetimesz. Unlike Tobler's method, the predictions are notconstrained to live within the original data range,so there tends to be "ringing" effects.
See the references for more details.
Value
A data frame with columnsx,y, andzgiving the smoothed valuez for locations (x, y).Currently the (x, y) values form a grid, but this is notguaranteed in the future.
Author(s)
Tom Minka
References
W.F. Eddy and A. Mockus. An example of the estimation and display of a smoothly varyingfunction of time and space - the incidence of disease mumps.Journal of the American Society for Information Science,45(9):686-693, 1994.https://web.eecs.utk.edu/~audris/papers/jasis.pdf
W. R. Tobler. Smooth pycnophylactic interpolation forgeographical regions.Journal of the American StatisticalAssociation 74:519-530, 1979.
Examples
# compare to the example for match.mapdata(state, package = "datasets")data(votes.repub)z = votes.repub[, "1900"]m = map("state", fill = TRUE, plot = FALSE)# use a small span to fill in, but not smooth, the data# increase the resolution to get better resultsfit = smooth.map(m, z, span = 1/100, merge = TRUE, ave = TRUE)mat = tapply(fit$z, fit[1:2], mean)gray.colors <- function(n) gray(rev(0:(n - 1))/n)par(bg = "blue")filled.contour(mat, color.palette = gray.colors, nlev = 32, asp = 1)# another way to visualize:image(mat, col = gray.colors(100))# for a higher degree of smoothing:# fit = smooth.map(m, z, merge = TRUE, ave = TRUE)# interpolation, state averages are preserved:# fit = smooth.map(m, z, merge = TRUE, ave = TRUE, type = "interp")United States State Boundaries Map
Description
This database produces a map of the states of the United States mainlandgenerated from US Department of the Census data (see the reference).
Usage
data(stateMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
US Department of Commerce, Census Bureau,County Boundary File,computer tape, available from Customer Services,Bureau of the Census, Washingdon DC 20233.
See Also
map.
Examples
map('state', fill = TRUE, col = palette())United States State Population Cartogram Map
Description
This database produces a cartogram of the states of the United Statesmainland based on CartoDraw, roughly proportional to population (seereferences).
state.carto.center are coordinates of the state centersfor annotation purposes.
Usage
data(stateMapEnv)data(state.carto.center)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
CartoDraw,http://www.computer.org/csdl/trans/tg/2004/01/v0095-abs.html
See Also
map.
Examples
map('state.carto', fill = TRUE, col = palette())FIPS state codes for US 48 State Map
Description
A database matching FIPS codes to maps package state names.
Usage
data(state.fips)Format
A list with 6 components, namely "fips", "ssa", "region", "division","abb" and "polyname", containing the US Census Bureau FIPS, SSA, REGIONand DIVISION numbers, the standard state abbreviation and the respectivestate polygon name. Note that "fips" is represented as an integer, so any leading zero (which is part of the fips code) is not shown by default.
See Also
United States State Visibility Base Map
Description
This database produces a map of the states of the United Statesmainland. The Visibility Base Map was created by Mark Monmonierto provide simplified state shapes with sufficient areas to allowannotations in even the small states.
state.vbm.center are coordinates of the state centersfor annotation purposes. The states are alphabetically ordered, in the same order as the map. So state names can be matched via e.g.map(state.vbm, plot=FALSE)$name.
Usage
data(state.vbmMapEnv)data(state.vbm.center)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
Mark Monmonier and George Schnell,"The Study of Population",Elements, Patterns, Processes. Charles E. Merrill. Columbus, OH. 1982.
See Also
map.
Examples
map('state.vbm', fill = TRUE, col = palette())Database of US cities
Description
This database is of us cities of population greater than about 40,000.Also included are state capitals of any population size.
Format
A list with 6 components, namely "name", "country.etc", "pop", "lat","long", and "capital", containing the city name, the state abbreviation,approximate population (as at January 2006), latitude, longitude andcapital status indication (0 for non-capital, 1 for capital, 2 for statecapital.
NOTE
Some of the city names may be out of date. Please sendany corrections to the package maintainer.
See Also
United States Coast Map
Description
This database produces a map of the United States mainland generated fromUS Department of the Census data (see the reference).
Usage
data(usaMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
US Department of Commerce, Census Bureau,County Boundary File,computer tape, available from Customer Services,Bureau of the Census, Washingdon DC 20233.
See Also
map.
Examples
map('usa')Low (mid) resolution World Map
Description
This world map (updated in 2013) is imported from the public domain Natural Earth project (the 1:50m resolution version). It replaces a much older version based on the CIA World Data Bank II data.The old legacy data is still available in the packagemapdata (v2.3.0).
Usage
data(worldMapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR_WORLD) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
Details
As of version 3.1, theworld database no longer contains any lakes. These have been moved to a separate database calledlakes.The legacy world map (dating from around 1990) has been removed from the package and is now available from themapdata package in two different resolutions (worldHires and worldLores).
Source
The Natural Earth data set is in the public domain and available fromhttps://www.naturalearthdata.com.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
See Also
Examples
# notice how some polygons extend beyond the [-180,180] interval:map('world', fill = TRUE, col = 1:10)# if you wrap at [-180,180], you also can get a clean closure of Antarcticamap('world', fill = TRUE, col = 1:10, wrap=c(-180,180) )Database of world cities
Description
This database is primarily of world cities of population greater thanabout 40,000. Also included are capital cities of any population size, andmany smaller towns.
Usage
data(world.cities)Format
A list with 6 components, namely "name", "country.etc", "pop", "lat","long", and "capital", containing the city name, the country name,approximate population (as at January 2006), latitude, longitude andcapital status indication (0 for non-capital, 1 for capital, 2 for ChinaMunicipalities, and 3 for China Provincial capitals)
NOTE
Some of the country names and city names may be out of date. Please sendany corrections to the package maintainer.
Source
The data were originally obtained from Stefan Helders' website (http://www.world-gazetteer.com), which no longer exists. There are no recent updates available.
See Also
Pacific Centric Low resolution World Map
Description
This is an alternative version of theworld database based on latitudes [0, 360), which then has the PacificOcean in the centre of the map.
Usage
data(world2MapEnv)Format
The data file is merely a character string whichspecifies the name of an environment variable which contains thebase location of the binary files used by the map drawing functions.This environment variable (R_MAP_DATA_DIR_WORLD for the datasets in themaps package) is set at package load timeif it does notalready exist. Hence setting the environment variable before loadingthe package can override the default location of the binary datasets.
NOTE
This data set is in fact largely obsolete. Often the same (more general) result can be obtained by using wrapping:
map("world", wrap=c(0,360))
This will also work fine withfill=TRUE or any other appropriate longitude interval (e.g.c(-90,270)).
However,world2 is useful when settingxlim to an interval crossing the 180 meridian.
Source
The public domain Natural Earth data set is available fromhttps://www.naturalearthdata.com.
References
Richard A. Becker, and Allan R. Wilks,"Maps in S",AT&T Bell Laboratories Statistics Research Report [93.2], 1993.
Richard A. Becker, and Allan R. Wilks,"Constructing a Geographical Database",AT&T Bell Laboratories Statistics Research Report [95.2], 1995.
See Also
Examples
map('world2', xlim = c(100, 300))map.axes()# xlim is performed before wrapping:map('world', wrap=c(0,360), xlim = c(100, 300))# so to emulate "world2":ww2 <- map('world', wrap=c(0,360), plot=FALSE, fill=TRUE)map(ww2, xlim = c(100, 300), fill=TRUE)