r - 绘制带孔的 "donut"多边形

标签 r plot ggplot2

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

最佳答案

外方正方形逆时针方向:

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

关于r - 绘制带孔的 "donut"多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088138/

相关文章:

r - 如何使 PCA 矢量箭头加粗(更宽)?

r - plyr summarize 只调用全局函数

r - Affymetrix 自定义 CDF 段错误

r - 通过 id 变量计算滚动总和,缺少时间点

r - 在ggplot2中通过labeller=label_wrap包裹长轴标签

javascript - 在半圆内绘制点

r - 制作箱线图时如何在函数内部的ggplot2中对组使用aes_string

r - 在 R 中从列表创建多个饼图

r - 不同的分位数 : Boxplot vs. Violinplot

r - 网格排列标题中的绘图