使用地图包创建具有剪切边界的等值区域地图的奇怪结果

时间:2014-07-31 18:11:27

标签: r maps choropleth

当我绘制纽约所有郡的地图时,我得到了一个正确的等值线图。然而,当我剪辑地图时,颜色看似随机。这是一个例子,我只是根据县名将县分为5个类别。

library(maps)
library(mapproj)
library(RColorBrewer)

map1 <- map("county", region="New York", plot=FALSE)
ny <- c(1:62)
ny2 <- data.frame(ny)

#define map colors
clr <- (brewer.pal(5, "Spectral"))

#define quantiles
map2 <- within(ny2, quartile <- as.integer(cut(ny, quantile(ny,probs=0:5/5), include.lowest=TRUE)))
map2$colorbuckets <- cut(map2$quartile, breaks=5)


#all of ny - colors are correct
map("county", border="gray", regions = "New York", fill=TRUE, projection="simpleconic", 
par=c(30,45), col=clr[map2$colorbuckets])
box()

#subset of ny - colors are not correct, seemingly random
map("county", regions="New York", xlim=c(-74.5,-73), ylim=c(40.48,43.9),  
border="gray", fill=TRUE, exact=TRUE, col=clr[map2$colorbuckets])
box()

1 个答案:

答案 0 :(得分:0)

#this code works 

library(maps)
library(mapproj)
library(RColorBrewer)

nymap <- map("county", region="New York", plot=FALSE)
ny <- c(1:62)
ny2 <- data.frame(ny)

#define map colors
clr <- (brewer.pal(5, "Spectral"))

#define quantiles
ny3 <- within(ny2, quartile <- as.integer(cut(ny, quantile(ny,probs=0:5/5), include.lowest=TRUE)))
ny3$colorbuckets <- cut(map2$quartile, breaks=5)
ny3$names <- nymap$names 

#all of ny - colors are correct
map("county", border="gray", regions = "New York", fill=TRUE, projection="simpleconic", 
    par=c(30,45), col=clr[nymap$colorbuckets])
box()

#create inset map, don't plot it but use it to merge with the complete list of county names and colors
inset1 <- map("county", regions="New York", xlim=c(-74.5,-73), ylim=c(40.48,43.9), plot=FALSE)
inset2 <- data.frame(inset1$names)
inset3 <- rename(inset2, c(inset1.names="names"))
inset4 <- merge(ny3,inset3,by="names")


#plot inset map - colors are now correct
map("county", regions="New York", xlim=c(-74.5,-73), ylim=c(40.48,43.9),  
    border="gray", fill=TRUE, col=clr[inset4$colorbuckets])
box()