密谋"甜甜圈"带孔的多边形

时间:2016-01-29 15:29:58

标签: r plot ggplot2

我想在ggplot2中制作类似甜甜圈的填充多边形,中心是透明的。我认为最好的方法是将外部内部多边形放入一个形状,使用" stem"连接两个多边形,然后填充这个形状。 (想象一下,如果必须绘制两个同心圆,而不用将笔从页面上抬起,则必须绘制干线。)请参见下面的示例。但问题是它仍然填充多边形的内部!有人知道为什么会这样吗?

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

1 个答案:

答案 0 :(得分: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()