使用 ggplot2 绘制地图 - 创建掩码填充一个不包含单个国家/地区的框

map with ggplot2 - create mask filling a box excluding a single country

是否可以在 ggplot 中有一个图层作为 ggmap 图层的掩码? Here 他们在 ggmap 上添加了一个国家多边形。

我正在寻找的是该国家/地区将是一个 "hole" 层(具有 alpha)覆盖除该国家/地区以外的所有内容。在某种程度上与上面的例子相反。该答案中的代码(添加并更新了透明度以使用 geom_cartogram)。

library(mapdata)
library(ggmap)
library(ggplot2)
library(ggalt)

# Get Peru map
Peru <- get_map(location = "Peru", zoom = 5, maptype="satellite") 

# This is the layer I wish to put over the top
coast_map <- fortify(map("worldHires", fill = TRUE, plot = FALSE)) 

# Subset data for Peru
peru.coast <- subset(coast_map, region == "Peru")

# Draw a graphic
ggmap(Peru) +
  geom_cartogram(data = peru.coast, map = peru.coast, aes(x = long, y = lat, map_id = region),
           fill="white", color="grey", alpha=.1) +
  xlim(-86, -68) +
  ylim(-20, 0) + 
  labs(x = "Longitude", y = "Latitude") +
  coord_map() +
  theme_classic()

有没有办法在 ggplot2 中填充除多边形以外的所有内容?

Is there a way to fill everything but a polygon in ggplot2?

这个方法可能有点不正统,但总之:

library(mapdata)
library(ggmap)
library(ggplot2)
library(raster)
ggmap_rast <- function(map){
  map_bbox <- attr(map, 'bb') 
  .extent <- extent(as.numeric(map_bbox[c(2,4,1,3)]))
  my_map <- raster(.extent, nrow= nrow(map), ncol = ncol(map))
  rgb_cols <- setNames(as.data.frame(t(col2rgb(map))), c('red','green','blue'))
  red <- my_map
  values(red) <- rgb_cols[['red']]
  green <- my_map
  values(green) <- rgb_cols[['green']]
  blue <- my_map
  values(blue) <- rgb_cols[['blue']]
  stack(red,green,blue)
}
Peru <- get_map(location = "Peru", zoom = 5, maptype="satellite") 
data(wrld_simpl, package = "maptools")
polygonMask <- subset(wrld_simpl, NAME=="Peru")
peru <- ggmap_rast(Peru)
peru_masked <- mask(peru, polygonMask, inverse=T)
peru_masked_df <- data.frame(rasterToPoints(peru_masked))
ggplot(peru_masked_df) + 
  geom_point(aes(x=x, y=y, col=rgb(layer.1/255, layer.2/255, layer.3/255))) + 
  scale_color_identity() + 
  coord_quickmap()

通过 this, this, and questions/answers.


What I am looking for is the surroundings with a transparent fill layer and Peru with alpha=1

如果首先想到这很容易。然而,后来我看到并记住了 geom_polygon 不太喜欢有孔的多边形。幸运的是,包 ggpolypath 中的 geom_polypath 可以。然而,它会在 grid.Call.graphics(L_path, x$x, x$y, index, switch(x$rule, winding = 1L..。” ggmap 的默认面板扩展出错。

所以你可以

library(mapdata)
library(ggmap)
library(ggplot2)
library(raster)
library(ggpolypath) ## plot polygons with holes
Peru <- get_map(location = "Peru", zoom = 5, maptype="satellite") 
data(wrld_simpl, package = "maptools")
polygonMask <- subset(wrld_simpl, NAME=="Peru")
bb <- unlist(attr(Peru, "bb"))
coords <- cbind(
  bb[c(2,2,4,4)],
  bb[c(1,3,3,1)])
sp <- SpatialPolygons(
  list(Polygons(list(Polygon(coords)), "id")), 
  proj4string = CRS(proj4string(polygonMask)))
sp_diff <- erase(sp, polygonMask)
sp_diff_df <- fortify(sp_diff)  

ggmap(Peru,extent="normal") +
  geom_polypath(
    aes(long,lat,group=group),
    sp_diff_df, 
    fill="white",
    alpha=.7
  )