理所当然,问题的代码行在这里:
mapnames <- map("county",plot=FALSE)[4]$names
colorsmatched <- d$colorBuckets [na.omit(match(mapnames ,d$stcon))]
有没有人建议如何生成一个适当长度的矢量,该矢量与地图库中NY,NJ,CT和PA的县数相匹配?我想合并我拥有的计数数据,并为我没有信息的县提供零。
我正在尝试按照此处所述的教程:http://www.thisisthegreenroom.com/2009/choropleths-in-r/
以下代码执行,但它不能正确匹配我的数据集与maps_counties数据,或者它没有按照我期望的顺序绘制它。例如,较大NYC区域的结果区域没有显示密度,而PA中的随机区域显示最高密度。
我的数据表的一般格式是:
county state count
fairfield connecticut 17
hartford connecticut 6
litchfield connecticut 3
new haven connecticut 12
...
...
westchester new york 70
yates new york 1
luzerne pennsylvania 1
请注意,这些数据按州和县的顺序排列,包括CT,NJ,NY和&amp ;;的数据。 PA。
首先,我读了我的数据集:
library(maps)
library(RColorBrewer)
d <- read.table("gissum.txt", sep="\t", header=TRUE)
#Concatenate state and county info to match maps library
d$stcon <- paste(d$state, d$county, sep=",")
#Color bins
colors = brewer.pal(5, "PuBu")
d$colorBuckets <- as.factor(as.numeric(cut(d$count,c(0,10,20,30,40,50,300))))
这是我的匹配
mapnames <- map("county",plot=FALSE)[4]$names
colorsmatched <- d$colorBuckets [na.omit(match(mapnames ,d$stcon))]
绘图:
map("county"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = colors[d$colorBuckets[na.omit(match(mapnames ,d$stcon))]]
,fill = TRUE
,resolution = 0
,lty = 0
,lwd= 0.5
)
map("state"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = "black"
,fill=FALSE
,add=TRUE
,lty=1
,lwd=2
)
map("county"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = "black"
,fill=FALSE
,add=TRUE
, lty=1
, lwd=.5
)
title(main="Respondent Home ZIP Codes by County")
我确信我遗漏了一些基本的东西:地图功能绘制项目的顺序 - 但我似乎无法弄明白。谢谢您的帮助。如果您需要更多信息,请与我们联系。
答案 0 :(得分:0)
通过将数据与选择状态的地图中的数据合并,可以找到解决问题的方法。这是你在找什么?
library(maps);
library(RColorBrewer);
# Create Dummy Data Frame to Play With
d = rbind(c('fairfield','connecticut',17),c('westchester','new york',70), c('luzerne','pennsylvania',1));
d = data.frame(d);
names(d) = c("county", "state", "count");
d$count = as.numeric(as.character(d$count));
d$stcon = paste(d$state, d$county, sep=",");
# Extract mapnames for States
mapnames2 = map("county",c("new york","new jersey", "connecticut", "pennsylvania"),plot=FALSE)[4]$names;
mapnames2 = data.frame(mapnames2);
names(mapnames2) = "stcon";
# Merge with d
d = merge(mapnames2, d, all = T);
d$count[is.na(d$count)] = 0;
# Color bins
colors = brewer.pal(5, "PuBu");
d$colorBuckets = as.factor(as.numeric(cut(d$count,c(0,10,20,30,40,50,300))));
map("county"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = colors[d$colorBuckets]
,fill = TRUE
,resolution = 0
,lty = 0
,lwd= 0.5
)
map("state"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = "black"
,fill=FALSE
,add=TRUE
,lty=1
,lwd=2
)
map("county"
,c("new york","new jersey", "connecticut", "pennsylvania")
,col = "black"
,fill=FALSE
,add=TRUE
, lty=1
, lwd=.5
)
title(main="Respondent Home ZIP Codes by County")