【问题标题】:plotting "donut" polygons with holes绘制带孔的“甜甜圈”多边形
【发布时间】:2016-05-07 09:38:32
【问题描述】:

我想在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

【问题讨论】:

  • 好问题和好标题!

标签: r plot ggplot2


【解决方案1】:

外面的正方形是逆时针方向的:

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()

【讨论】:

  • 完美,谢谢!我不完全理解其中的原因,但我只是顺其自然。
  • 方向是唯一可以区分要填充在重叠多边形或带有孔的多边形中的多边形部分。您可以通过再次将新点按逆时针方向轻松地在甜甜圈内添加一个较小的正方形。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2010-10-17
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 2013-04-11
  • 2014-05-15
相关资源
最近更新 更多