r - ggplot 省略了多边形孔

标签 r ggplot2

我很难让 ggplot 绘制具有孔洞的多边形。下面进行演示。首先使用 git clone https://github.com/geotheory/volcano 获取 shapefile .下一个:

require(ggplot2); require(ggmap); require(dplyr); require(maptools)
v = readShapePoly('volcano/volcano.shp')
v@proj4string = CRS('+proj=longlat +datum=WGS84')

# confirm polygons spatially exclusive (don't overlap)
plot(t(bbox(v)), type='l', lwd=8)
plot(v, col=paste0(colorRampPalette(c('grey','red'))(8),'dd'), add=T)

enter image description here

看起来还可以。 A dd如果被多个多边形遮挡,alpha 应该使线条不可见。现在让我们在 ggplot 中尝试。
d = fortify(v) %>% as_data_frame()
bb = bbox(v)
toner = get_stamenmap(c(bb[1,1], bb[2,1], bb[1,2], bb[2,2]), zoom=11, maptype='toner')
ggmap(toner) + geom_polygon(data=d, aes(long, lat, group=group, fill=id), alpha=.5)

enter image description here

中心多边形必须重叠,因为底层 map 在中心完全被遮挡。让我们检查漏洞的强化数据:
d %>% select(id, hole) %>% table()
   hole
id  FALSE TRUE
  0   278    0
  1   715    0
  2   392  388
  3   388  331
  4   390  265
  5   265  387
  6   328  125
  7   125    0

看起来不错,所以让我们尝试分别可视化它们。
i = 3
plot(v[i,], col='red') 
ggplot(filter(d, id == i-1)) + geom_polygon(aes(long, lat, group=group, col=hole), fill=NA)
ggplot() + geom_polygon(data=filter(d, id==i-1), aes(long,lat, group=group))

enter image description here

似乎出了什么问题。 ggplot 似乎忽略了这些漏洞。除非是shapefile的问题。任何建议如何诊断/解决这个问题?

最佳答案

"hadley/ggplot2: plotting polygon shapefiles"说“...,保留了空洞状态,但ggplot2不使用此信息”。幸运的是,ggspatial包裹,"Fish & Whistle: Holes in ggplot polygons"教我,好像解决了一些问题,比如重叠问题。 (“Biggin Hill”标签上方的白色区域不是由于 ggspatial 包,因为它也在我的环境中的 ggplot(d) + geom_polygon(aes(long, lat, group = group, fill = id)) 上)

devtools::install_github("paleolimbot/ggspatial")

library(ggspatial)

ggmap(toner) + geom_spatial(data=v, aes(fill=id), alpha=.8)

enter image description here

关于r - ggplot 省略了多边形孔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202010/

相关文章:

r - R 中出现 "Variable Lengths Differ"错误的原因是什么?

r - 最大化包含 pbivnorm 的似然函数

r - 有没有办法在 facet_grid 图中的 y 轴名称之外绘制小平面条名称(切换 y)?

r - 在ggplot2中的条之间放置刻度线

使用 dcast reshape 数据?

r - R 中各组的树状图的颜色分支(无 h 或 k 元素)

r - 如何从列表中的多个向量中选择多个元素

r - geom_ribbon 中的渐变

r - HTML 中的 Knitr 和图形标题

r - 生成 R ggplot 线图,其颜色/类型以不同变量为条件