使用包對映中的 map() 進行基本地圖製作
包 maps
中的函式 map()
為使用 R 建立地圖提供了一個簡單的起點。
基本世界地圖可以繪製如下:
require(maps)
map()
通過將顏色引數 col
設定為顏色的字元名稱或十六進位制值,可以更改輪廓的顏色:
require(maps)
map(col = "cornflowerblue")
為了用 tihuan4 中的顏色填充土地,我們可以設定 fill = TRUE
:
require(maps)
map(fill = TRUE, col = c("cornflowerblue"))
當 fill = TRUE
也被設定時,可以向 col
提供任意長度的向量:
require(maps)
map(fill = TRUE, col = c("cornflowerblue", "limegreen", "hotpink"))
在上面的示例中,col
的顏色任意分配給地圖中表示區域的多邊形,如果顏色少於多邊形,則顏色將被回收。
我們還可以使用顏色編碼來表示統計變數,其可以可選地在圖例中描述。這樣建立的地圖稱為等值線。
下面的 choropleth 示例將 map()
的第一個引數設定為 database
,county
和 state
使用內建資料集 unemp
和 county.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)
}