对于我目前正在进行的项目,我必须根据使用R的某些输入绘制纽约市社区的热图。我搜索了该主题并发现在R中,有一个名为&#34的包;映射"将允许您很容易地绘制美国各州的热图。但是,我不知道如何为一个城市绘制类似的热图,特别是在这里,纽约市?任何建议都受到高度赞赏。
答案 0 :(得分:7)
SO上有很多答案可以帮助您填充带有颜色的shapefile多边形。我同意@ 42-你没有表现出任何工作/努力,但这可能对其他人寻求与纽约社区地区数据做类似的事情有所帮助。所以,为了更大的利益:
library(rgeos)
library(maptools)
library(geojsonio)
library(ggplot2)
# this is the geojson of the NYC community districts
URL <- "http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nycd/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson"
fil <- "nyc_community_districts.geojson"
if (!file.exists(fil)) download.file(URL, fil)
nyc_districts <- geojson_read(fil, what="sp")
# the @data slot of nyc_districts has 2 fields. BoroCD is the district #
nyc_districts_map <- fortify(nyc_districts, region="BoroCD")
# let's see which id is what
mids <- cbind.data.frame(as.data.frame(gCentroid(nyc_districts, byid=TRUE)),
id=nyc_districts$BoroCD)
gg <- ggplot()
gg <- gg + geom_map(data=nyc_districts_map, map=nyc_districts_map,
aes(x=long, y=lat, map_id=id),
color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + geom_text(data=mids, aes(x=x, y=y, label=id), size=2)
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
gg
# example choropleth
# we'll just make the map look like the Flash map on the NYC site
colorize <- function(x) {
switch(substr(x, 1, 1),
`1`="#86e3ff",
`2`="#fffe9b",
`3`="#ffc75f",
`4`="#e7ceff",
`5`="#dffd8b")
}
choro <- data.frame(district=nyc_districts@data$BoroCD,
fill=sapply(nyc_districts@data$BoroCD, colorize))
gg <- ggplot()
gg <- gg + geom_map(data=nyc_districts_map, map=nyc_districts_map,
aes(x=long, y=lat, map_id=id),
color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + geom_map(data=choro, map=nyc_districts_map,
aes(fill=fill, map_id=district),
color="#2b2b2b", size=0.15)
# in a real choropleth you'd make colors map to values
# so i'm definitely leaving you some work to do vs just
# copy/paste for fun and profit
gg <- gg + scale_fill_identity()
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
gg
# better color palette
library(viridis)
# make up some fill data
set.seed(1492)
choro <- data.frame(district=nyc_districts@data$BoroCD,
fill=sample(100, nrow(nyc_districts@data)))
gg <- ggplot()
gg <- gg + geom_map(data=nyc_districts_map, map=nyc_districts_map,
aes(x=long, y=lat, map_id=id),
color="#2b2b2b", size=0.15, fill=NA)
gg <- gg + geom_map(data=choro, map=nyc_districts_map,
aes(fill=fill, map_id=district),
color="#2b2b2b", size=0.15)
gg <- gg + scale_fill_viridis(name="Better title\nthan 'fill'")
gg <- gg + coord_map()
gg <- gg + ggthemes::theme_map()
gg <- gg + theme(legend.position=c(0.1,0.5))
gg