R语言 在多边形中为ggplot蒙版打一个洞

v9tzhpje  于 2023-06-19  发布在  其他
关注(0)|答案(2)|浏览(76)

我在做一个ggplot的面具。如何在不使用GIS程序的情况下删除在ggplot上绘制的圆内的区域?我有一个data.frame,用于在图和圆上制作边界框,如下所示:

library(ggplot2)
bndBox <- data.frame(x=c(-Inf,Inf,Inf,-Inf),
                     y=c(Inf,Inf,-Inf,-Inf),
                     id="bnd")

hole <- data.frame(
  x = cos(seq(0, 2*pi, length.out = 360)),
  y = sin(seq(0, 2*pi, length.out = 360)),
  id="circle"
)

porthole <- rbind(bndBox,hole)

ggplot() + 
  # I want to be able to see this point
  geom_point(aes(x = 0,y = 0)) +
  # But not this point
  geom_point(aes(x = -1,y = 0)) +
  geom_polygon(data=porthole, 
               aes(x = x, y = y, fill = id),
               inherit.aes = FALSE)
yftpprvb

yftpprvb1#

更新了答案,以考虑顺时针方向前进的闭合多边形会形成一个孔。

library(ggplot2)

bndBox <- data.frame(x=c(-Inf,-Inf,Inf,Inf, -Inf),
                     y=c(-Inf,Inf,Inf,-Inf, -Inf),
                     id="bnd")

bndBox <- data.frame(x=c(-1,1,1,-1, -1),
                     y=c(-1,-1,1,1, -1),
                     id="bnd")

hole <- data.frame(
  x = cos(seq(0, 2*pi, length.out = 360)) * 0.95,
  y = sin(seq(0, 2*pi, length.out = 360)) * 0.95,
  id="circle"
)

porthole <- rbind(bndBox,hole)

ggplot() + 
  geom_polygon(data=porthole, 
               aes(x = x, y = y), fill = "red")+
  geom_point(aes(x = 0, y = 0)) +
  coord_fixed() +
  theme_void()

创建于2023-06-15带有reprex v2.0.2

gfttwv5a

gfttwv5a2#

我可以用sf做我想做的事情,但我希望不要走这条路,因为我发现代码很难理解,并且觉得geom_polygon()应该能够处理它。下面是一个繁琐的解决方案:

library(ggplot2)
library(sf)

bndBox <- data.frame(x=c(-1,1,1,-1),
                     y=c(1,1,-1,-1),
                     id="bnd")
hole <- data.frame(
  x = cos(seq(0, 2*pi, length.out = 360)),
  y = sin(seq(0, 2*pi, length.out = 360)),
  id="circle"
)

portholeSF <- st_sfc(
  st_polygon(
    list(
      hole = cbind(
        c(hole$x,hole$x[1]), 
        c(hole$y,hole$y[1])
      ),
      bnd = cbind(
        c(bndBox$x,bndBox$x[1]), 
        c(bndBox$y,bndBox$y[1])
      )
    )
  )
)

ggplot() + 
  # I want to see this point
  geom_point(aes(x = 0,y = 0)) +
  # But not this point
  geom_point(aes(x = -0.75,y = 0.75)) +
  geom_sf(data = portholeSF)

相关问题