map()包中的函数maps为使用R创建映射提供了一个简单的起点。
基本的世界映射可以绘制如下:
require(maps) map()
可以通过将颜色参数设置为颜色col的字符名称或十六进制值来更改轮廓的颜色:
require(maps) map(col = "cornflowerblue")
要用颜色填充陆地,col我们可以设置fill = TRUE:
require(maps)
map(fill = TRUE, col = c("cornflowerblue"))还可以将colwhenfill = TRUE设置为任何长度的向量:
require(maps)
map(fill = TRUE, col = c("cornflowerblue", "limegreen", "hotpink"))在上面的示例中,来自col的颜色被任意分配给表示区域的映射中的多边形,如果颜色少于多边形,则颜色将被回收。
我们还可以使用颜色编码来表示统计变量,可以在图例中对其进行描述。这样创建的映射被称为“ choropleth”。
下面的示例示例设置的第一个参数map(),使用内置数据集的数据并以白色覆盖状态线时,为databaseto"county"和"state"为失业设置颜色代码:unempcounty.fips
require(maps)
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"
# Code improvements by Hack-R (hack-r.github.io)
# 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("paleturquoise", "skyblue", "cornflowerblue", "blueviolet", "hotpink", "darkgrey")
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
par(mar=c(1, 1, 2, 1) + 0.1)
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.1,
projection="polyconic")
title("unemployment by county, 2009")
legend("topright", leg.txt, horiz = TRUE, fill = colors, cex=0.6)
}