绘制带洞的“甜甜圈”多边形

3

我想在ggplot2中制作类似甜甜圈的填充多边形,其中心透明。我认为最好的方法是将外部和内部多边形放入一个形状中,并用“茎”连接两个多边形,然后填充此形状。(想象一下,如果你不抬笔离开页面,你需要画两个同心圆的茎。)请参见下面的示例。问题是它仍然填充了多边形的内部!有人知道为什么会这样吗?

library(ggplot2)

#generates a dataframe of points for a regular polygon, with the starting point duplicated at the end. 
NgonPoints <- function(center=c(0,0), radius=1, nsides=100, start=0, end=2)
{
  tt <- seq(start*pi, end*pi, length.out=nsides+1)
  data.frame(x = round(center[1] + radius * cos(tt),5), 
             y = round(center[2] + radius * sin(tt),5))
}

#get points for an inner and outer square
twosquares <- rbind(NgonPoints(nsides=4, radius=1), NgonPoints(nsides=4, radius=.5))


test <- ggplot(data=twosquares, mapping=aes(x=x,y=y)) +
  coord_fixed(ratio=1)+
  xlim(-1,1)+
  ylim(-1,1)+
  theme_bw() +
  theme(axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

#this traces the correct path
test <- test + geom_path()
test
#but this fills the inside of the inner square
test <- test + geom_polygon(alpha=.5)
test

plot results


很棒的问题和很棒的标题! - Gregor Thomas
1个回答

4

外部正方形逆时针定向:

twosquares$id <- seq_len(nrow(twosquares))
ggplot(data=twosquares, mapping=aes(x=x,y=y)) + 
  geom_text(aes(label=id))

因此,为了避免填充内部正方形,您必须顺时针定位它:
ggplot(data=twosquares[c(1:6,9,8,7,10), ], mapping=aes(x=x,y=y)) +
  geom_polygon()

太好了,谢谢!虽然我不完全理解这样做的原因,但我会接受并执行。 - user278411
方向是唯一能够区分多边形部分填充在重叠的多边形或有孔多边形中的东西。您可以通过再次将新点逆时针定向来轻松地在甜甜圈内添加一个较小的正方形。 - krlmlr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接