我有一个有色三角形的彩色噪音。 现在,我希望多边形可以像'" cookie cutter"在圣诞节。导致由多边形路径包围的三角形噪声。
如何剪切与多边形边框重叠的所有像素,然后将其另存为pdf?
我想出了两个想法:
可重复的示例:
library(magrittr)
library(ggplot2)
library(SDMTools)
polyGony <- c(0,0,100,50,50,100) %>% matrix(ncol=2,byrow = T) %>% as.data.frame()
deltaN <- 200 #grid width
sp1<-seq(1,100,length=deltaN)
sp2<-seq(1,100,length=deltaN)
sp<-expand.grid(x=sp1,y=sp2)
set.seed(1337)
sp$z <- sample(1:30,nrow(sp),replace = T)
# Method 1
outin = SDMTools::pnt.in.poly(sp[,1:2],polyGony)
outin$z <- sp$z
pointsInsideTri <- outin[outin$pip==1,-3]
p <- ggplot(pointsInsideTri, aes(x, y)) +
geom_raster(aes(fill = z)) +
scale_fill_gradientn(colours=c("#FFCd94", "#FF69B4", "#FF0000","#4C0000","#000000"))
p + geom_polygon(data = polyGony, aes(V1,V2),color="black", fill=NA) + theme(aspect.ratio = 1)
# Method 2
outSQ <-c(0,0,100,0,100,100,0,100)
invPolyGony <- c(outSQ,0,0,100,50,50,100) %>% matrix(ncol=2,byrow = T) %>% as.data.frame()
p <- ggplot(sp, aes(x, y)) +
geom_raster(aes(fill = z)) +
scale_fill_gradientn(colours=c("#FFCd94", "#FF69B4", "#FF0000","#4C0000","#000000"))
p + geom_polygon(data = invPolyGony, aes(V1,V2) ,colour="black", fill="white") + theme(aspect.ratio = 1)
答案 0 :(得分:4)
我现在知道问题所在。为了填充多边形之外的所有东西,路径(中间的孔)需要顺时针“运行”,外边框需要逆时针运行。
我做了一个简单的例子。我们有一个星形的多边形。我希望明星之外的一切都是红色的。
star <- c(25.000,1.000,31.000,18.000,49.000,18.000,35.000,29.000,40.000,46.000,
25.000,36.000,10.000,46.000,15.000,29.000,1.000,18.000,19.000,18.000) %>% matrix(ncol=2, byrow=T)
star <- rbind(star,star[1,])
rim <- c(0,0, 50,0, 50,50,0,50,0,0) %>% matrix(ncol=2, byrow=T)
datapolyM <- rbind(rim,star) %>% as.data.frame()
names(datapolyM) <- c("x","y")
ggplot(datapolyM, aes(x=x, y=y)) +
geom_polygon(fill="red", colour="black")
现在让我们转动星星的路径顺时针运行:请尊重第二行中的apply和reverse命令:
star <- c(25.000,1.000,31.000,18.000,49.000,18.000,35.000,29.000,40.000,46.000,
25.000,36.000,10.000,46.000,15.000,29.000,1.000,18.000,19.000,18.000) %>% matrix(ncol=2, byrow=T) %>% apply(2, rev)
star <- rbind(star,star[1,])
rim <- c(0,0, 50,0, 50,50,0,50,0,0) %>% matrix(ncol=2, byrow=T)
datapolyM <- rbind(rim,star) %>% as.data.frame()
names(datapolyM) <- c("x","y")
datapolyM$id <- "a"
ggplot(datapolyM, aes(x=x, y=y)) +
geom_polygon(fill="red")