我想创建一张美国地图(可能是热图),以显示各州之间某种特征的频率。我不确定使用什么包或我的数据是否是正确的形式。我的数据在表tf
中tf
AB AK AL AN AR AZ CA CO CT DC DE EN FL GA HI IA ID IL IN KS
1 21 31 1 12 56 316 53 31 16 7 1 335 63 11 42 29 73 40 2
在大多数情况下,我的缩写是美国(除少数加拿大实例外)。在地图上以图形方式显示此内容的最佳建议方法是什么?
现在我如何获得每种颜色少于50的粒度?
答案 0 :(得分:8)
两个包: 地图,ggplot2。 有一个很好的例子: ?map_data()
刚开始:
tf= structure(list(state = structure(1:14, .Label = c("AK", "AL",
"AR", "AZ", "CA", "CO", "CT", "DE", "FL", "GA", "IA", "IL", "IN",
"KS"), class = "factor"), num = c(21L, 31L, 12L, 56L, 316L, 53L,
31L, 7L, 335L, 63L, 42L, 73L, 40L, 2L), region = structure(c(2L,
1L, 4L, 3L, 5L, 6L, 7L, 8L, 9L, 10L, 13L, 11L, 12L, 14L), .Label = c("alabama",
"alaska", "arizona", "arkansas", "california", "colorado", "connecticut",
"delaware", "florida", "georgia", "illinois", "indiana", "iowa",
"kansas"), class = "factor")), .Names = c("state", "num", "region"
), class = "data.frame", row.names = c(NA, -14L))
require(maps);require(ggplot2)
states <- map_data("state")
tfmerged <- merge(states, tf, sort = FALSE, by = "region")
tfmerged <- tfmerged[order(tfmerged$order), ]
qplot(long, lat, data = tfmerged, group = group, fill = num,
geom="polygon")
然后填写状态信息的剩余部分。
答案 1 :(得分:8)
使用spplot
的另一种方法:
library(maps)
library(maptools)
library(sp)
首先读取数据并添加一个包含状态名称的列:
txt <- "AB AK AL AN AR AZ CA CO CT DC DE EN FL GA HI IA ID IL IN KS
1 21 31 1 12 56 316 53 31 16 7 1 335 63 11 42 29 73 40 2"
dat <- stack(read.table(text = txt, header = TRUE))
names(dat)[2] <-'state.abb'
dat$states <- tolower(state.name[match(dat$state.abb, state.abb)])
然后您获取地图并将其转换为SpatialPolygons
:
mapUSA <- map('state', fill = TRUE, plot = FALSE)
nms <- sapply(strsplit(mapUSA$names, ':'), function(x)x[1])
USApolygons <- map2SpatialPolygons(mapUSA, IDs = nms, CRS('+proj=longlat'))
现在您可以添加数据中的信息:
idx <- match(unique(nms), dat$states)
dat2 <- data.frame(value = dat$value[idx], state = unique(nms))
row.names(dat2) <- unique(nms)
USAsp <- SpatialPolygonsDataFrame(USApolygons, data = dat2)
最后你绘制它:
spplot(USAsp['value'])
添加了图片