我可以使用ggplot创建一个县地图。我想使用这个地图数据,并映射作为县聚合的新边界。例如,我的一个等价任务是使用这个县地图数据集来映射州边界(“区域”变量),而不是县边界(我将使用另一个变量来聚合县)。
只需更改ggplot中的组就不起作用了。我相信我可能需要根据我用来聚合的变量创建新的多边形形状,但我不确定。有关如何做到这一点的任何想法?非常感谢任何帮助!
library(ggplot2)
# load county map data
m.county <- map_data("county")
head(m.county)
long lat group order region subregion
1 -86.50517 32.34920 1 1 alabama autauga
2 -86.53382 32.35493 1 2 alabama autauga
3 -86.54527 32.36639 1 3 alabama autauga
4 -86.55673 32.37785 1 4 alabama autauga
5 -86.57966 32.38357 1 5 alabama autauga
6 -86.59111 32.37785 1 6 alabama autauga
# map county data with county borders
ggplot(data = m.county) +
geom_polygon(aes(x=long, y=lat,group=group))
答案 0 :(得分:1)
您可以使用gUnaryUnion
中的library(rgeos)
来合并多边形,但是当您使用库maps
中的地图时,这需要几个步骤:
get_map
library(ggplot2)
library(sp)
library(rgdal)
library(maps)
library(mapdata)
# adapted from
# http://stackoverflow.com/questions/26062280/converting-a-map-object-to-a-spatialpolygon-object
require(sp)
require(maptools)
county <- map("county", fill = TRUE)
library(sp)
head(county$names)
county.sp <- map2SpatialPolygons(county, IDs = as.factor(county$names),
proj4string = CRS("+proj=longlat +datum=WGS84"))
# Add information data of the polygons
region <- sapply(strsplit(county$names, ","), function(x) x[1])
subregion <- sapply(strsplit(county$names, ","), function(x) x[2])
subregion[is.na(subregion)] <- region[is.na(subregion)]
# Create the SpatialPolygonsDataFrame
county.sp.data <- SpatialPolygonsDataFrame(
county.sp,
data = data.frame(region = region,
subregion = subregion),
match.ID = FALSE)
gUnaryUnion
因为库maps
中的映射在拓扑方面不干净,所以需要使用缓冲区来清除它。
library(rgeos)
# Because of topology problems
county.sp.data.buffer <- gBuffer(county.sp.data, byid = TRUE, width = 0)
# Merge polygons according to region
county.region <- gUnaryUnion(county.sp.data.buffer,
id = county.sp.data.buffer@data$region)
使用fortify
能够使用ggplot
county.fortify <- fortify(county.region)
ggplot(data = county.fortify) +
geom_polygon(aes(x=long, y=lat, fill=group)) +
guides(fill = FALSE)