我有两个多边形,我希望在ggplot2
中合并其轮廓。我怎么做?
目前我设法直观地合并多边形,但我的解决方案不适用于大纲:
tmp <- structure(list(y.min = c(68, 72), y.max = c(72, 73), x.min = c(-160,
-130), x.max = c(-120, -120), ID = structure(1:2, .Label = c("a",
"b"), class = "factor")), .Names = c("y.min", "y.max", "x.min",
"x.max", "ID"), row.names = 1:2, class = "data.frame")
## Object tmp contains limits for the polygons I want to merge
## Transform them ready for ggplot2:
pols <- lapply(1:nrow(tmp), function(i){
data.frame(ID = tmp$ID[i], y = c(tmp$y.max[i], tmp$y.max[i], tmp$y.min[i],
tmp$y.min[i]), x = c(tmp$x.min[i], tmp$x.max[i], tmp$x.max[i], tmp$x.min[i]))
})
pols <- do.call(rbind, pols)
## I can use the ID as a group argument to plot the polygons.
## I get rid of the outlines by using NA as color:
library(ggplot2)
ggplot(data = pols, aes(x = x, y = y)) + geom_point() +
geom_polygon(aes(group = ID), alpha = 0.3, color = NA)
## I however would like to merge these polygons and only plot the outlines without filling:
ggplot(data = pols, aes(x = x, y = y)) + geom_point() +
geom_polygon(aes(group = ID), alpha = 0, color = "black") +
annotate("segment", x = -130, y = 71, xend = -125, yend = 71.8,
arrow = arrow(length = unit(0.5, "cm"))) +
annotate("text", x = -130, y = 70.8, label = "I want to get rid of this line")
答案 0 :(得分:0)
这是一种做法。对于空间包,这是最简单的,正如@Gregor在评论中指出的那样。我使用了spatstat
:
library(spatstat)
polys <- lapply(1:nrow(tmp), function(i) {
owin(c(tmp$x.min[i], tmp$x.max[i]), c(tmp$y.min[i], tmp$y.max[i]))
})
merged.poly <- union.owin(polys[[1]], polys[[2]])
merged.poly <- data.frame(x = merged.poly$bdry[[1]]$x, y = merged.poly$bdry[[1]]$y)
ggplot() + geom_polygon(data = merged.poly, aes(x = x, y = y),
color = "black", alpha = 0) + geom_point(data = pols, aes(x = x, y = y))