在ggmap中控制自定义shapefile集的背景地图显示

时间:2015-10-28 12:20:56

标签: r ggplot2 gis shapefile ggmap

我正在处理与以下摘录相对应的数据集:

# Data sourcing -----------------------------------------------------------

# Download an read US state shapefiles
tmp_shps <- tempfile(); tmp_dir <- tempdir()
download.file("http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_state_20m.zip",
              tmp_shps)
unzip(tmp_shps, exdir = tmp_dir)

# Libs
require(rgdal); require(ggplot2)

# Read
us_shps <- readOGR(dsn = tmp_dir, layer = "cb_2014_us_state_20m")
# Prepare data set for ggplot2
us_shps_frt <- fortify(us_shps, region = "NAME")

在该数据集中,我自定义了一组shapefile,如下例所示:

map_shps <- ggplot(data = us_shps_frt[grep("South", us_shps_frt$id),]) +
  geom_polygon(aes(x = long, y = lat, group = group,
                                fill = id)) +
  coord_equal() +
  ggtitle("Odd Map") +
  theme_map()

Odd Map

鉴于上面选择了奇怪的形状文件,我想拟合一个背景图,它可以整齐地覆盖多边形的最大范围。最初,我试图通过以下方式实现这一目标:

# Get box for the map
bbox <- make_bbox(lon = long, lat = lat,
                  data = us_shps_frt[grep("South", us_shps_frt$id),],
                  f = 0.5)
map_backgr  <- get_map(bbox, maptype = "roadmap", zoom = 5,
                       source = "google", scale = 2, messaging = TRUE)
map_backgr <- ggmap(map_backgr, extent = "normal", maprange = FALSE)

然后生成地图:

map_backgr +
  geom_polygon(data = us_shps_frt[grep("South", us_shps_frt$id),],
               aes(x = long, y = lat, group = group,
                   fill = id)) +
  coord_equal() +
  ggtitle("Odd Map with Background") +
  theme_map()

生成的图形不适合多边形:

Messy map

我有兴趣调整背景地图,使其与多边形完全匹配。特别是我想通过下图中标记的红线裁剪/缩短背景:

What to delete

1 个答案:

答案 0 :(得分:1)

想法1:使用雄蕊,它们支持奇形怪状的地图:

Stamen

dat <- us_shps_frt[grep("South", us_shps_frt$id),]

ggmap(get_stamenmap(c(min(dat$long), min(dat$lat), 
                      max(dat$long), max(dat$lat)), 
                    zoom = 6)) +
geom_polygon(data = dat,
             aes(x = long, y = lat, group = group,
                 fill = id)) +
ggtitle("Odd Map with Background") 

想法2:剪切您的Google Maps地图:

Google

dat <- us_shps_frt[grep("South", us_shps_frt$id),]

ggmap(get_map(c(min(dat$long), min(dat$lat), max(dat$long), max(dat$lat)))) +
geom_polygon(data = dat,
             aes(x = long, y = lat, group = group,
                 fill = id)) +
ggtitle("Odd Map with Background") +
coord_map(xlim = c(min(dat$long), max(dat$long)),
          ylim = c(min(dat$lat), max(dat$lat)))

但是这个还差一点,我认为您需要使用projection = "..."的{​​{1}}和parameters = "..."