r - 等值线邮政编码

标签 r zipcode choropleth

我正在尝试创建弗吉尼亚州部分地区的邮政编码分区统计表以显示一些公司数据。除了最后一行 aes(fill = Growth) 之外,我可以让所有内容正确运行。在那里,我收到一个错误:

Error: Aesthetics must either be length one, or the same length as the dataProblems:growth

这是我的数据:

我的代码:

library(ggplot2)
library(maptools)
library(rgdal)
library(plyr)

#set working directory
setwd("F:/Dropbox/Zip Codes")

#load Shapefile NOVA
Zips <- readOGR(dsn="F:/Dropbox/Zip Codes", layer="NOVA")

#load Company Data of Zip Codes
Company <- read.csv("Data.csv")

#set to data.frame
Company_df <- data.frame(Company)

#create growth vector
growth = Company_df[,'Growth']

#merge growth vector into Zips
Zips$growth = growth

#ggplot
Nmap = ggplot(Zips) +
aes(x = long, y = lat, group=group) +
geom_polygon() +
aes(fill = growth)
Nmap

最佳答案

我组织你的目录结构有点不同。尽管互联网上有较旧的代码片段,但您不需要将数据绑定(bind)到数据框。但是,您确实需要 fortify与 ggplot 一起使用的多边形。另外,read.csv生成一个 data.frame,因此您无需从该调用中重新生成一个 data.frame。

library(ggplot2)
library(maptools)
library(rgdal)
library(ggthemes)

setwd("~/Development/nova_choro")

zips <- readOGR(dsn="zip_codes/NOVA.shp", layer="NOVA")
company <- read.csv("data.csv")

# this makes the polygons usable to ggplot2
# and by using ZCTA5CE10 as the region id, 
# you can then use that equivalent id field 
# from the actual company data frame for the
# choropleth colors

zips_map <- fortify(zips, region="ZCTA5CE10")

gg <- ggplot()
# draw the base map polygons
gg <- gg + geom_map(data=zips_map, map=zips_map,
                    aes(x=long, y=lat, map_id=id),
                    color="#7f7f7f", fill="white", size=0.25)
# fill in the polygons
gg <- gg + geom_map(data=company, map=zips_map,
                    aes(fill=Growth, map_id=zip_code_area),
                    color="#7f7f7f", size=0.25)
# better color scheme
gg <- gg + scale_fill_distiller(palette="Greens")
# no "slashes" in the legend boxes
gg <- gg + guides(fill=guide_legend(override.aes=list(colour=NA)))
# use an actual projection (there may be a better one for NOVA
gg <- gg + coord_map()
# get rid of map chart junk
gg <- gg + theme_map()
gg

enter image description here

我做了一些检查,VA 使用修改后的兰伯特圆锥等角投影,因此您可以替换默认的墨卡托 coord_mapgg <- gg + coord_map("lambert", lat0=38.34427, lat1=39.14084)如果您愿意的话,这应该足够接近官方机构使用的内容。

关于r - 等值线邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31641945/

相关文章:

r - 阿拉斯加和夏威夷未正确格式化 R 中的县等值线 map

plotly - 在破折号中调整图形大小

sql - R 和 SQL Server 2008

r - 防止 R 嵌套列表转换为命名向量

r - 将邮政编码映射到 R 中各自的城市和州?

php - 使用 MySQL 面向 future 的邻近搜索

r - 从 glm 拟合的 lapply 列表中提取 p 值

r - 如何检查矩阵的列是否遵循R中的预定顺序?

javascript - GoogleMaps addlistener zip 弹出窗口?

javascript - 交互式 d3 邮政编码分区统计表 - WA 州