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